user17949931
user17949931

Reputation:

Memory deallocation in C

I've allocated a two-dimensional pointer array. I need to deallocate this pointer array w/o using array notation e.g., indices or offset values.

main.c

#include "practice.h"

int main() {
   int **A, **B, **C; // declare arrays.
   initNumSpace(A, B, C); // allocate space of arrays.
   freeNumSpace(A, B, C); // dealloc space of arrays.
}

practice.h

#ifndef PRACTICE
#define PRACTICE

/**
 * Function to alloc space of params.
 * @param A is a 2D pointer array.
 * @param B is a 2D pointer array.
 * @param C is a 2D pointer array.
*/
void initNumSpace();

/**
 * Function to free allocated space of params.
 * @param A is a 2D pointer array.
 * @param B is a 2D pointer array.
 * @param C is a 2D pointer array.
*/
void freeNumSpace();

#endif

practice.c

#include <stdlib.h>
#include "practice.h"

// allocate space of arrays.
void initNumSpace(int **A, int **B, int **C) {
    A = malloc(sizeof(int*) * 10);
    B = malloc(sizeof(int*) * 10);
    C = malloc(sizeof(int*) * 10);

    int** a = A;
    int** b = B;
    int** c = C;

    for (int i = 0; i < 10; i++) {
       *a = malloc(sizeof(int) * 10);
       *b = malloc(sizeof(int) * 10);
       *c = malloc(sizeof(int) * 10);

       a++;
       b++;
       c++;
   }
}

// de-alloc space
void freeNumSpace(int **A, int **B, int **C) {
   int** a = A;
   int** b = B;
   int** c = C;

   int* p = *a;
   int* q = *b;
   int* r = *c; 

   for (int i = 0; i < 10; i++) {
       p = *a;
       q = *b;
       r = *c;
           free(p);
           free(q);
           free(r);
       a++;
       b++;
       c++;
    }

    free(A);
    free(B);
    free(C);
}

There is an error output in Valgrind, specifying misuse of allocated or de-allocated space. I would like to know if the program can better de-allocate the space without misuse of memory.

Upvotes: 2

Views: 191

Answers (1)

chux
chux

Reputation: 153303

Save time. Enable all warnings

B = malloc(sizeof(int*) * 10);

Warning: assignment to 'int' from 'void *' makes integer from pointer without a cast [-Wint-conversion]

Fix with:

int** A, B, C; --> int **A, **B, **C;

Allocate to the referenced object, not type

Less error prone. Easier to review and maintain.

// A = malloc(sizeof(int*) * 10);
A = malloc(sizeof *A * 10);

Upvotes: 2

Related Questions