free is used to release a block of dynamically allocated memory. After freeing the memory, you should not use the pointer to that memory again, as it no longer points to valid memory.
Syntax:
void free(void* ptr);
ptr: A pointer to a previously allocated memory block.
Example:
free(arr); // Frees the previously allocated memory
Complete Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
// Step 1: Allocate memory for an array of 5 integers using malloc
int* arr = (int*) malloc(10 * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Step 2: Initialize the array
for (int i = 0; i < 10; i++) {
arr[i] = i * 10; // Fill array with some values
}
// Step 3: Print the array
printf("Array values (after malloc): ");
for (int i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// Step4: Free the allocated memory
free(arr);
return 0;
}