Skip to content

➰ Realloc Memory Allocation

Feldwor edited this page Jul 21, 2021 · 12 revisions

Example

tmp = realloc(orig, newsize);
if (tmp == NULL)
{
    // could not realloc, but orig still valid
}
else
{
    orig = tmp;
}

Example of implementation
https://github.com/vaido-world/C-Language-Tutorial/blob/master/README.md#backlashes_conversion_in_asciic

realloc

Examination

On success, returns the pointer to the beginning of newly allocated memory.
To avoid a memory leak, the returned pointer must be deallocated with free() or realloc().
On failure, returns a null pointer. [source]

Useful Comment #1

You are correct that directly assigning the return value of realloc to your only copy of the original pointer is a bad practice. Not only do you lose the ability to free the memory if realloc failed (I would call this the lesser issue); you also lose the data that your pointer pointed to.

For some programs this may not matter (e.g. if you're just going to terminate and abort the entire operation on allocation failures, which may or may not be acceptable practice, and which is a whole topic in itself) but in general you need to first store the result of realloc to a separate temp variable, and only overwrite the original pointer variable after you check that it succeeded. [source]

Useful comment #2

Pointer a still point to the same address, but the content is changed.

That's because realloc() may first try to increase the size of the block that a points to. However, it can instead allocate a new block, copy the data (or as much of the data as will fit) to the new block, and free the old block. You really shouldn't use a after calling b = realloc(a, 200000 * sizeof(int)) since the realloc call may move the block to a new location, leaving a pointing to memory that is no longer allocated. Use b instead. [source]

Useful comment #3

realloc on failure keeps the original pointer and size. realloc on success may not (and often does not) return the exact same pointer as the input. [source]

Learning and Reference of C language. Public Domain.
Also available in CC0 or MIT License.

Clone this wiki locally