free() Release dynamically allocated memory

free() Release dynamically allocated memory

free() releases dynamic storage; free(NULL) does nothing. Never access freed storage or free it twice; aliases remain; nested allocations are not freed.

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

📝 Syntax

void free(void *ptr);

⚙️ Parameters

ptr RequiredThe original pointer returned by an allocation function, or NULL.

Returns: No value is returned. If ptr is NULL, no action occurs.

▶ Example

Edit the C code below and click Run; the server compiles and executes it:

Output:

Value before free: 42
Memory released
⚠️ Warning Do not dereference the pointer after freeing it or free it twice. Passing a pointer that is not from dynamic allocation, or not to the block's start, also causes undefined behavior.
💡 Tip Setting the pointer to NULL after release helps prevent misuse through that variable, but it does not clear any other aliases.

📚 Related Tutorials

❓ FAQ

QIs free(NULL) safe?
AYes. The standard explicitly makes it a no-op, so a separate NULL test before free() is unnecessary.
QWhat happens if I free the same pointer twice?
AIt causes undefined behavior, potentially corrupting allocator state or crashing. Each valid allocation must be released exactly once.
QDoes setting a pointer to NULL after free make everything completely safe?
ANo. Setting only the current variable to NULL prevents that variable from accessing the old address; other aliases may still dangle, and resources inside the block are not released automatically. Define ownership and lifetimes clearly, release nested resources before the block itself, and avoid duplicate releases on every path.
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%

🙏 帮我们做得更好

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

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