Free Function

Releases a block of memory previously allocated by a call to the malloc, calloc, or realloc function.
void Free(
    _Pre_ _Frees_ptr_opt_ _Post_ _Null_ void* ptr
);

Parameters

Parameter Description
ptr A pointer to the memory block to be freed. If ptr is NULL, the function does nothing.

Return Value

This function does not return a value.

Remarks

The Free function releases a block of memory of at least 8 bytes that has been allocated by one of the heap allocation functions (malloc, calloc, or realloc). Attempting to free an invalid pointer (a pointer not allocated by these functions, or a pointer already freed) can lead to heap corruption.

After calling Free, the pointer ptr will point to a deallocated memory location. It is good practice to set the pointer to NULL immediately after freeing the memory to prevent accidental use of the dangling pointer.

This function is typically part of the standard C runtime library and is used extensively in C and C++ programming for dynamic memory management.

Example


#include <stdio.h>
#include <stdlib.h>

int main() {
    char *buffer;

    // Allocate memory for 100 characters
    buffer = (char *)malloc(100 * sizeof(char));
    if (buffer == NULL) {
        perror("Failed to allocate memory");
        return 1;
    }

    // Use the allocated memory...
    printf("Memory allocated successfully.\n");
    sprintf(buffer, "This is a test string.");

    // Free the allocated memory
    free(buffer);
    printf("Memory freed.\n");

    // It's good practice to set the pointer to NULL
    buffer = NULL;

    // Attempting to free NULL does nothing
    free(buffer);

    return 0;
}
            

See Also


API Version: Windows 10, version 1507

Header: stdlib.h

Library: Use C Runtime library