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.
| Category | stdlib.h utilities |
|---|---|
| Kind | Library function |
| Header | <stdlib.h> |
| C standard | C89 / C90 |
📝 Syntax
void free(void *ptr);
⚙️ Parameters
| ptr Required | The 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 stdlib.h functions
📚 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.