Skip to content

Commit

Permalink
json2cbor: don't use the buffer variable after realloc()
Browse files Browse the repository at this point in the history
There's a discussion in the C and C++ communities whether you're allowed
to use the values of pointers that have been deallocated, if you don't
dereference them. Some argue that it is Undefined Behaviour in spite of
the numeric value stored in the variable not having changed.

Instead of arguing, let's just make sure we don't use the pointers after
they have become dangling. We only needed the offset of how far we've
written into the buffer to restore the state and we have a function that
returns exactly that.

Seen while debugging #259.

Drive-by keep the `buffersize` global variable unchanged until after
`realloc()` has returned with success.

Signed-off-by: Thiago Macieira <[email protected]>
  • Loading branch information
thiagomacieira committed Nov 7, 2024
1 parent 26c63e3 commit feba0c1
Showing 1 changed file with 2 additions and 1 deletion.
3 changes: 2 additions & 1 deletion tools/json2cbor/json2cbor.c
Original file line number Diff line number Diff line change
Expand Up @@ -328,13 +328,14 @@ CborError decode_json(cJSON *json, CborEncoder *encoder)
err = cbor_encode_double(encoder, json->valuedouble);

if (err == CborErrorOutOfMemory) {
ptrdiff_t offset = cbor_encoder_get_buffer_size(&container, buffer);
buffersize += 1024;
uint8_t *newbuffer = realloc(buffer, buffersize);
if (newbuffer == NULL)
return err;

*encoder = container; // restore state
encoder->data.ptr = newbuffer + (container.data.ptr - buffer);
encoder->data.ptr = newbuffer + offset;
encoder->end = newbuffer + buffersize;
buffer = newbuffer;
goto encode_double;
Expand Down

0 comments on commit feba0c1

Please sign in to comment.