Memory deallocation in C

Viewed 58

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.

in .h file exists int** A, B, C;

void initNumSpace() {
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++;
   }
}

After allocating memory space. I'm having trouble deallocating memory within my program. The deallocation code looks like

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

I am assuming there is an error here. The Valgrind program is delivering an error " Conditional jump or move depends on uninitialized value(s)". This is the only space that I deallocate, or allocate memory.

1 Answers

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);
Related