0

What is the correct way to free a float ** like below.

e.g. float ** someArray

for(int i = 0; i < numberOfDimensions; i++)
    {
        somearray[i] = (float *) malloc(numberOfDimensions * sizeof(float));
    }
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
some_id
  • 29,466
  • 62
  • 182
  • 304

6 Answers6

4

If you have malloc'ed another round of memory and assigned it to each float pointer in the original array, then you should free them as well beforehand:

int i;
for (i = 0; i < numberOfDimensions; i++)
    free(someArray[i]);

// and free the container array only now

free(someArray);

P. s.: don't cast the return value of malloc.

Community
  • 1
  • 1
1

I believe you're expected to free the elements, and then free the array.

rsegal
  • 401
  • 3
  • 11
1

Go backwards:

for(int i = 0; i < numberOfDimensions; i++)
{
    free(somearray[i]);
}

free(somearray);
SheetJS
  • 22,470
  • 12
  • 65
  • 75
0

Well, in this case you simply free(someArray). Now, if you malloc'd more memory and added that to someArray, then you need to walk that array and free each object.

in other words if you:

for(int i=0; i< whatever; ++i) {
  someArray[i] = malloc(...
}

Then you need to walk it again and do frees before you free someArray.

David H
  • 40,852
  • 12
  • 92
  • 138
0

Just a simple 1-free() call:

free(someArray);
MByD
  • 135,866
  • 28
  • 264
  • 277
-1
for(int i = 0; i < numberOfDimensions; i++)
{
    free(somearray[i]);
    somearray[i] = NULL;
}

free(somearray);
somearray=NULL;

(somearray[i] = NULL) this line will break the link of each array element and finally (somearray=NULL) will break the link to the array. These two lines will free up the array of dynamic memory and the OS allocate this freed memory to some other process

Tarun
  • 11
  • 4
  • can you please improve the post? Instead of only posing a sample code, can you try to explain the reason behind writing the code? – Sourav Ghosh Nov 07 '16 at 13:32