C free() function

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;
}

C free() function – Interview Questions

Q 1: What is the use of free()?

Ans: To release dynamically allocated memory.

Q 2: What happens if free() is not used?

Ans: Memory leak occurs.

Q 3: Can we free memory twice?

Ans: No, it causes undefined behavior.

Q 4: What happens if free(NULL) is called?

Ans: Nothing happens.

Q 5: Why should pointers be set to NULL after free()?

Ans: To avoid dangling pointers.

C free() function – Objective Questions (MCQs)

Q1. What is the purpose of free() in C?






Q2. What happens if you call free() twice on the same pointer?






Q3. What should be done after freeing memory using free()?






Q4. Which memory areas can be freed using free()?






Q5. What happens if you pass NULL to free()?






Related C free() function Topics