I have a static pointer
static int **2dArr;
and then I allocate memory for 2d array.
How can I free that memory and replace it with another array?
//////////////////////////////////////////////////////////////////////////
void func(int **arr) {
int i,j,k,tmp;
int **destMatrix = NULL;
destMatrix = (int**) malloc(N * sizeof(int *));
if ((destMatrix == NULL)) {
fprintf(stderr, "out of memory\n");
exit(2);
}
for (i = 0; i < N; i++) {
destMatrix[i] = (int*) malloc(N * sizeof(int));
if (destMatrix[i] == NULL) {
fprintf(stderr, "out of memory\n");
exit(2);
}
}
for(i = 0; i < N; ++i) {
free(arr[i]);
}
free(arr);
arr = NULL;
arr = destMatrix;
}
//////////////////////////////////////////////////////////////////////////
int main() {
2dArr = (int**) malloc(N * sizeof(int *));
if (2dArr== NULL) {
fprintf(stderr, "out of memory\n");
exit(2);
}
for (i = 0; i < N; i++) {
2dArr[i] = (int*) malloc(N * sizeof(int));
if (2dArr[i] == NULL) {
fprintf(stderr, "out of memory\n");
exit(2);
}
}
func(2dArr);
// try to print new array, access violation
}
I free memory and try to replace the pointer. But then I have a access violation. How can I do it correctly?
Couple things:
void func(int ***arr) {free((*arr)[i]);and
free(*arr);*arr = destMatrix;++iinstead ofi++at the for loop at the end of func ) this doesn’t actually matter — see the comment belowI debugged these issues using Valgrind, check it out.
Working code is below: