realloc() Resize a dynamically allocated block
realloc() Resize a dynamically allocated block
realloc() resizes and may move a block; use a temporary pointer. Failure with size > 0 preserves it; new bytes are uninitialized; zero-size rules vary.
| Category | stdlib.h utilities |
|---|---|
| Kind | Library function |
| Header | <stdlib.h> |
| C standard | C89 / C90 |
📝 Syntax
void *realloc(void *ptr, size_t size);
⚙️ Parameters
| ptr Required | NULL, or a pointer previously returned by malloc(), calloc(), or realloc() and not yet freed. |
|---|---|
| size Required | The new total size in bytes. |
Returns: When size > 0, returns a pointer to the resized block, possibly different from ptr, on success. If size > 0 and allocation fails, returns NULL with the original block unchanged and still requiring free. See the notes for the special C89 behavior when size == 0.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
10 20 30 40 50
⚠️ Warning When size > 0, store the result in a temporary pointer first. Assigning directly to ptr loses the original pointer and leaks the block if allocation fails.
⚠️ Warning Under the C89 behavior documented on this page, realloc(ptr, 0) with a non-null ptr deallocates ptr. Do not subsequently access or free the original pointer, and do not interpret a NULL result as evidence that the old block is still allocated; avoid relying on zero-size realloc.
💡 Tip Newly added bytes after growth are uninitialized. After shrinking, only the contents up to the smaller of the old and new sizes are preserved.
🏷️ Related stdlib.h functions
📚 Related Tutorials
❓ FAQ
QIs the original block still usable if realloc fails?
AOnly when size > 0 and NULL is returned because allocation failed does the original block remain unchanged, usable, and in need of eventual free. When size == 0 and ptr is non-null, the C89 behavior documented here deallocates ptr, so the original pointer must not be accessed or freed again; zero-size realloc should therefore be avoided.
QDoes realloc always return the original address?
ANot necessarily; the block may move. After success, use only the returned pointer, not the old block pointer or pointers into its old storage.
QCan I read the newly added region immediately after realloc grows a block?
ANo. After successful growth, the original contents are preserved up to the smaller of the old and new sizes, while the added region is uninitialized and must be assigned values before being read. The function may also move the block, so use the returned pointer and update any related pointers into the block.