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.

Categorystdlib.h utilities
KindLibrary function
Header<stdlib.h>
C standardC89 / C90

📝 Syntax

void *realloc(void *ptr, size_t size);

⚙️ Parameters

ptr RequiredNULL, or a pointer previously returned by malloc(), calloc(), or realloc() and not yet freed.
size RequiredThe 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏