Reputation: 21
For example this is the codes for a function file, named fnx.c
, where func()
will be called from the main function. How should I free the TempArray
here while return the double pointer to the main function at the same time?
int * * TempArray; //global variable in this file
static void CreatePointer(int row, int col) {
int r;
TempArray = malloc(sizeof(int * ) * (row));
for (r = 0; r < row; r++) {
TempArray[r] = malloc(sizeof(int) * (col));
}
}
static void DestroyPointer() {
free(TempArray);
TempArray = NULL;
}
int * * func(int * * OriArray, int row, int col, int r_offset, int c_offset) {
int r, c;
CreatePointer(row, col);
for (r = 0; r < row; r++) {
for (c = 0; c < col; c++) {
TempArray[r][c] = OriArray[r + r_offset][c + c_offset];
}
}
//destroy TempArray??
return TempArray;
}
Upvotes: 0
Views: 1177
Reputation: 182
if you want to use this point(TempArray) after called from the main function,you can not destroy it(TempArray).Only when you do not want to use this point datas,you can destroy it. you can test like this:
main()
{
int *p = func(oriArray,row,col,r_offset,c_offset);
for (int r = 0; r < row; r++){
for(int c = 0; c < col; c++){
printf("%d",p[r][c]);
}
}
DestroyPointer();
}
Hope it helps !
Upvotes: 1
Reputation: 2627
You should free all the rows before freeing up TempArray
.
static void DestroyPointer (int row)
{
for (int r = 0; r < row; r++)
{
free(TempArray[r]);
}
free(TempArray);
TempArray = NULL;
}
But You shouldn't destroy the pointer before returning it,
because dereferencing it after that in main
will cause undefined behaviour.
Upvotes: 0
Reputation: 1174
main()
, call CreatePointer()
main()
, call func()
func()
, when you don't need TempArray
anymore, call DestroyPointer()
And your DestroyPointer()
is wrong. You'll have memory leaks. It should be something like :
static void DestroyPointer (int row)
{
for (int r = 0; r < row; r++)
{
free(TempArray[r]);
}
free(TempArray);
}
Upvotes: 3