-
Notifications
You must be signed in to change notification settings - Fork 0
➰ Realloc Memory Allocation
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
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]
TutorialsPoint Reference for C standard library is always useful.
https://www.tutorialspoint.com/c_standard_library/index.htm
General C language overview can be found on Geeks for Geeks.
https://www.geeksforgeeks.org/c-programming-language/
Advanced In-depth book on C language.
Extreme C: Taking you to the limit in Concurrency, OOP, and the most advanced capabilities of C
Quick simplistic tutorials on C language can be found here.
https://www.tutorialspoint.com/cprogramming/index.htm
https://www.programiz.com/c-programming
Learning and Reference of C language.
Public Domain.
Also available in CC0 or MIT License.