0

Help!

I am using malloc to create an array on the heap... but I can't seem to get the compiler to recognize the call to "free"!

/******************************************** * Program Name: callFree.c * Created By: Myriddin * Creation Date: Friday, March 29, 2015 * * Program Purpose: This program will be * a place where I can practise with calling * free! * * * Modification History: * * Name: Date: Modification: * * **********************************************/ include stdio.h include stdlib.h

//The syntax of the include files stdio and stdlib had to be changed so they would appear in posting....

int main(int argc, char *argv[]) {

int intFlag = 1;
int n = 5;

//Version 1: Array is instantiated on the stack
//int arrayX[n];


//Version 2: Array is instantiated on the heap
int *arrayX = malloc(sizeof(int) * n);

//Load Array:
arrayX[0]  = 23;
arrayX[1] = 42;
arrayX[2] = 4;
arrayX[3] = 16;
arrayX[4] = 8;
arrayX[5] = 15;

for(int i = 0; i < n; i++)
{
    printf("Element: %d: %d\n", i, arrayX[i]);
}

//You need to call free on array that is in the heap!
if(intFlag == 1)
{
    for(int i = 0; i < n; i++)
        free(arrayX[i]);
    free(arrayX);    
}





return 0;

}


callFree.c:50:18: error: incompatible integer to pointer conversion passing 'int' to parameter of type 'void *' [-Werror,-Wint-conversion]

free(arrayX[i]);
^~~~~~~~~

Thanks, Myriddin

1
  • I believe your problem is that you're trying to free the elements of the array and then freeing the array as a whole. You should free the entire array at once. Drop the for loop and it should work. { free(arrayX); } – Cliff B Mar 27 '15 at 18:31
1

Per man free (3),

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed.

First, arrayX[i] is not a pointer; it's actually of type int in this case. And even if it was a pointer, it was not really returned by a call to a function of the malloc family.

0

That's because free(arrayX[i]); isn't a pointer, but *arrayX is a pointer to an int.

if you modify as below, everything works well.

  //You need to call free on array that is in the heap!
   if(intFlag == 1)
   {
    //for(int i = 0; i < n; i++)
    //    free(arrayX[i]);
    free(arrayX);    
   }

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .