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 <thiago.macieira@intel.com>
This commit is contained in:
Thiago Macieira
2025-03-11 18:24:45 -07:00
parent e072bc1d78
commit 2fc4c35f9d
+6 -4
View File
@@ -328,15 +328,17 @@ encode_double:
err = cbor_encode_double(encoder, json->valuedouble);
if (err == CborErrorOutOfMemory) {
buffersize += 1024;
uint8_t *newbuffer = realloc(buffer, buffersize);
ptrdiff_t offset = cbor_encoder_get_buffer_size(&container, buffer);
size_t newbuffersize = buffersize + 1024;
uint8_t *newbuffer = realloc(buffer, newbuffersize);
if (newbuffer == NULL)
return err;
*encoder = container; // restore state
encoder->data.ptr = newbuffer + (container.data.ptr - buffer);
encoder->end = newbuffer + buffersize;
encoder->data.ptr = newbuffer + offset;
encoder->end = newbuffer + newbuffersize;
buffer = newbuffer;
buffersize = newbuffersize;
goto encode_double;
}
return err;