Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

free memory outside a void function where it is allocated

Tags:

c

pointers

malloc

I have a void function

void foo(int *ptr) {
   //trying to allocate memory to hold 5 ints
   ptr = malloc(sizeof(int)*5):
   //I loop ptr and assign each with a value i =0 to 4;
}

In the main function I have this lines

int main() {
    int *num;
    //I called the function 
    foo(&(num));
    free(num);

   return 1;
}

I get munmap_chunk() invalid pointer error. I did try to dig in more information, but I could not figure this out. I know it will be basic for those who work in c. I was thinking I am passing by reference and it should work, but it is not. I am new to C, and so far has been a headache.

like image 467
user1986244 Avatar asked Mar 10 '26 06:03

user1986244


1 Answers

ptr is a local variable, his lifetime ends with the function, you need a pointer to pointer in order to alter num in main

   void foo(int **ptr) {
       //trying to allocate memory to hold 5 ints
       *ptr = malloc(sizeof(int)*5);
       //I look ptr and assign each with a value i =0 to 5;
   }
like image 196
David Ranieri Avatar answered Mar 11 '26 18:03

David Ranieri