1

Why is the passed variable "list" after performing the function "test" empty i.e. accessing the elements of list or freeing the pointer list result in a memory leak?

What am I missing?

int test(int** container)
{
    int numOfItems = 2;
    int* p1;
    int* p2;
    int j=0;

    container = (int**) malloc (sizeof(int*) * numOfItems);
    for(j=0;j<numOfItems;j++)
         container[j] = (int*) malloc (sizeof(int));

    *(container[0]) = 12;
    *(container[1]) = 13;
}

int main( int argc, const char* argv[] )
{ 
    int* list;
    test(&list);
}
Augmented Jacob
  • 1,567
  • 19
  • 45
Younes El Ouarti
  • 2,200
  • 2
  • 20
  • 31

1 Answers1

7
container = (int**) malloc (sizeof(int*) * numOfItems);

should be

*container = malloc (sizeof(int*) * numOfItems);

container is only a local variable, a copy of the int* list.

Also, you generally should not cast the return of malloc.

Community
  • 1
  • 1
Chostakovitch
  • 965
  • 1
  • 9
  • 33