Managing Memory: Freeing Allocated Memory for Pointer Arrays

10 Sep 2023 Balmiki Mandal 0 C Programming

Freeing Allocated Memory for an Array of Pointers

To free the memory allocated for an array of pointers, you need to iterate through each element of the array and free the memory allocated for each individual pointer. After that, you can free the memory allocated for the array itself.

Here's an example code snippet in C:

C-programming
#include <stdio.h>
#include <stdlib.h>

int main() {
    int i;
    int n = 5; // Assuming you have an array of 5 pointers

    // Allocate memory for an array of pointers
    char* array_of_pointers[n];

    for (i = 0; i < n; i++) {
        // Allocate memory for each individual pointer
        array_of_pointers[i] = (char*)malloc(20 * sizeof(char)); // Assuming each string has a maximum length of 19 characters
    }

    // ... Do operations with the array of pointers ...

    // Free the memory for each individual pointer
    for (i = 0; i < n; i++) {
        free(array_of_pointers[i]);
    }

    // Free the memory for the array of pointers
    return 0;
}

In this example, we first allocate memory for an array of pointers array_of_pointers. Then, we loop through each element and allocate memory for individual strings using malloc.

After performing operations with the strings, we free the memory for each individual string using free(array_of_pointers[i]). Finally, we free the memory for the array of pointers using return 0;.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.