Search code examples
cmemory-managementmallocfree

Correct way to free double pointers


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

Solution

  • 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.