LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

free a pointer to pointer

Hi

I'm using a two dimensional to store data, but when i have to define the array i don't know the dimensions of the array yet, so i have to use a pointer to a pointer to define the size of the array i want. I do the next:

        int **arraySegment = NULL;

        arraySegment = malloc (Conf.Vision.numLines*sizeof(int));
        for (x = 0 ; x < Conf.Vision.numLines ; x++)
                arraySegment[x] = malloc (Conf.Vision.numImages*sizeof(int));

So when i want to free arraySegment what do i have to do? Is it enough to use free (arraySegment); or do i have to do something like:

        for (x = 0 ; x < Conf.Vision.numLines ; x++)
                free (arraySegment [x]);
        free (arraySegment);

any suggestions? Thanks
0 Kudos
Message 1 of 5
(3,428 Views)

Every malloc() (or equivalent type of function eg calloc()) needs a corresponding free(), so yes you do need to use the code you suggested. (Strictly speaking you are allocating space for pointers, not integers - you might want to tidy up the sizeof() statements accordingly.)

JR

Message 2 of 5
(3,415 Views)
Thank you JR, one question what do you mean with "Strictly speaking you are allocating space for pointers, not integers - you might want to tidy up the sizeof() statements accordingly" that i should change the code in the first malloc because is not a reservation for int but for another pointer? something like:
 
     int **arraySegment = NULL;
        arraySegment = malloc (Conf.Vision.numLines*sizeof(int*)); (can i do this?)
        for (x = 0 ; x < Conf.Vision.numLines ; x++)
                arraySegment[x] = malloc (Conf.Vision.numImages*sizeof(int));
Regards
 
Juan
0 Kudos
Message 3 of 5
(3,388 Views)
Indeed you can do that. And you can do it on your last line as well, with the second malloc() in a loop.
 
JR
Message 4 of 5
(3,367 Views)

Thank you for your help JR

Regards

Juan

0 Kudos
Message 5 of 5
(3,344 Views)