Freeing memory

suggest change

Call free when dynamically allocated storage is no longer needed:

int *values = malloc(10 * sizeof *values);
if (values == NULL) {
    perror("malloc");
    return EXIT_FAILURE;
}

/* Use values. */

free(values);
values = NULL;

The call ends the lifetime of the allocated object. Any pointer to that allocation becomes dangling, and the allocation must not be accessed or freed again. Assigning NULL to one pointer does not update aliases that point to the same allocation.

Pass to free only a null pointer or a pointer value returned by a compatible allocation function that has not already been deallocated. Passing the address of an automatic object, a pointer into the middle of an allocation, or an already-freed pointer causes undefined behavior.

int value;
int *invalid = &value;
free(invalid); /* Undefined behavior: value was not dynamically allocated. */

free(NULL) is guaranteed to do nothing. Setting a pointer to NULL after freeing it can therefore make repeated cleanup of that particular pointer harmless, but it does not solve ownership errors or protect other aliases.

Prefer clear ownership: document which component is responsible for releasing each allocation, and arrange cleanup so that every successful allocation is released exactly once. Limiting a pointer's scope can prevent accidental later use, but free itself does not end the pointer variable's scope.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents