tpm2-software/tpm2-tss

Replace free() malloc() sequences with realloc

Opened this issue · 1 comments

Static code analysis gets confused by free() & malloc() sequences and claims use-after-free.

We can avoid this by using realloc instead; e.g.

free(object->misc.key.private.buffer);
object->misc.key.private.buffer = malloc(object->misc.key.private.size);

I think it might be because realloc error handling is cumbersome, meaning instead of the lines you showed you would have

            uint8_t *new_buffer = malloc(object->misc.key.private.size);
            goto_if_null2(new_buffer, "Out of memory.",
                    r, TSS2_FAPI_RC_MEMORY, error_cleanup);
            object->misc.key.private.buffer = new_buffer;

instead of

            free(object->misc.key.private.buffer);
            object->misc.key.private.buffer = malloc(object->misc.key.private.size);
            goto_if_null2(object->misc.key.private.buffer, "Out of memory.",
                    r, TSS2_FAPI_RC_MEMORY, error_cleanup);

But might be better in term of perfomance in case the zone allocated by malloc is already big enough to handle that, however, realloc include a memcpy when this is not the case which is useless, which might counter act any potential benefit of using realloc