Malloc () ing in the external function causes a memory leak

advertisements

This question already has an answer here:

  • c - passing pointers to a function 3 answers

I know this is a common problem, however in my case the answer is not that straightforward (or at least I think so).

What I want is to allocate memory for 10 integers (as seen in the scheme below).

Scheme:

                               _____HEAP_____
                              |              |
**numbers ----->  *number  ---|-->  int      |
                  *number  ---|-->  int      |
                  *number  ---|-->  int      |
                   ..         |              |
                  *number  ---|-->  int      |
                              |______________|

Code:

int** numbers;

void malloc_number(int* number){
    number = malloc(sizeof(int));
}

int main(){

    numbers = malloc(10*sizeof(int*));
    int n;
    for (n=0; n < 10; n++){
        //numbers[n] = malloc(sizeof(int)); // THIS WORKS
        malloc_number(numbers[n]);          // THIS DOESN'T
        free(numbers[n]);
    }
    free(numbers);
}

I don't seem to understand why this isn't working. In my mind numbers[n] that I pass to malloc_number is a pointer to some unallocated number. Then I use number = malloc(sizeof(int)); (number = numbers[n]) to allocate memory to that pointer.

What am I doing wrong?


   void malloc_number(int* number){
    number = malloc(sizeof(int));
   }

This function leaks memory. Remember C is pass-by-value and number argument is an object with automatic storage duration that got destroyed when malloc_number returns. If you want to modify a pointer through a function you have to pass a pointer to the pointer.