Nole Fan 81
Nole Fan 81

Reputation: 59

Free dynamically created 3d array in C

None of the answers I have found seem to address my issue. I am creating a dynamic 3d array in C and later freeing it. I can store and later access the data stored in this array using a nested for loop but I get an access violation when trying to free it using the same nested for loop setup. Where am I going wrong?

unsigned char ***buff1;
int r, c;
someFunction(&buff1, &r, &c);
for(int i = 0; i < r; ++i)
{
  for(int j = 0; j < c; ++j)
  {
    free(buff1[i][j]);
  }
  free(buff1[i]);
}
free(buff1);


someFunction(unsigned char**** buff, int *nR, int *nC)
{
  ...
  *buff = (SQLCHAR***)malloc(*nR * sizeof(SQLCHAR**));
  for(int i = 0; i < *nR; ++i)
  {
    (*buff)[i] = (SQLCHAR**)malloc(*nC * sizeof(SQLCHAR**));
    for(int j = 0; j < *nC; ++j)
    {
      (*buff)[i][j] = (SQLCHAR*)malloc(256);
    }
  }
}

Upvotes: 1

Views: 1688

Answers (3)

user2553780
user2553780

Reputation: 151

Your code looks pretty buggy. For starters you are calling someFunction(&buff1, &r, &c) while that function expects ints and not int *s. Later you dereference nR and nC and they aren't pointers.

I guess you should be getting some nasty warnings when compiling.

Upvotes: 1

Lidong Guo
Lidong Guo

Reputation: 2857

I try you code in this way,and it works good:

#include "stdio.h"
#include "stdlib.h"

int  someFunction (unsigned char**** buff, int *nR, int *nC)
{
  int i,j;
  *buff = (unsigned char ***)malloc(*nR * sizeof(char**));
  for(i = 0; i < *nR; ++i)
  {
    (*buff)[i] = (unsigned char**)malloc(*nC * sizeof(char**));
    for(j = 0; j < *nC; ++j)
    {
      (*buff)[i][j] = (unsigned char*)malloc(256);

      (*buff)[i][j][0] ='1';
    }
  }
}


int main()
{
unsigned char ***buff1;
int r = 3, c= 2,i,j;
someFunction(&buff1, &r, &c);
for( i = 0; i < r; ++i)
{
  for(j = 0; j < c; ++j)
  {
        printf("        %c",buff1[i][j][0]);
    free(buff1[i][j]);
  }
  free(buff1[i]);
}
free(buff1);
}

So, maybe the mistake is not happening in the code you are showing to us.

Upvotes: 2

user529758
user529758

Reputation:

Multiple things are wrong:

unsigned char**** buff

What is this, if not wrong? (Well, OK, not technically, but stylistically anyway...)

(SQLCHAR*)malloc(256);

isn't any better either, since you must not cast the return value of malloc() in C.

The third mistake is that you don't have a 3D array. You have a pointer-to-pointer-to-pointer. Ewww. Ugly. Why not allocate a true 3D array instead?

size_t xsize, ysize, zsize; // initialize these!
unsigned char (*arr)[ysize][zsize] = malloc(sizeof(*arr) * xsize);

Then all you need to do in order to free it is:

free(arr);

Honestly, isn't this way better?

Upvotes: 2

Related Questions