From e1837aec7b43c54ca9524cee1c497620d06f4a44 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Tue, 5 Nov 2024 16:52:27 -0800 Subject: [PATCH] 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 --- tools/json2cbor/json2cbor.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/tools/json2cbor/json2cbor.c b/tools/json2cbor/json2cbor.c index 090ee158..bb35108b 100644 --- a/tools/json2cbor/json2cbor.c +++ b/tools/json2cbor/json2cbor.c @@ -328,15 +328,17 @@ CborError decode_json(cJSON *json, CborEncoder *encoder) 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;