Skip to content

Commit 2fc4c35

Browse files
json2cbor: don't use the buffer variable after realloc()
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]>
1 parent e072bc1 commit 2fc4c35

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

tools/json2cbor/json2cbor.c

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -328,15 +328,17 @@ CborError decode_json(cJSON *json, CborEncoder *encoder)
328328
err = cbor_encode_double(encoder, json->valuedouble);
329329

330330
if (err == CborErrorOutOfMemory) {
331-
buffersize += 1024;
332-
uint8_t *newbuffer = realloc(buffer, buffersize);
331+
ptrdiff_t offset = cbor_encoder_get_buffer_size(&container, buffer);
332+
size_t newbuffersize = buffersize + 1024;
333+
uint8_t *newbuffer = realloc(buffer, newbuffersize);
333334
if (newbuffer == NULL)
334335
return err;
335336

336337
*encoder = container; // restore state
337-
encoder->data.ptr = newbuffer + (container.data.ptr - buffer);
338-
encoder->end = newbuffer + buffersize;
338+
encoder->data.ptr = newbuffer + offset;
339+
encoder->end = newbuffer + newbuffersize;
339340
buffer = newbuffer;
341+
buffersize = newbuffersize;
340342
goto encode_double;
341343
}
342344
return err;

0 commit comments

Comments
 (0)