Search code examples
arrayscmallocfree

C. malloc() and free() in function doesn't work


Can someone tell me, why I can't allocate memory to the struct array through the init() function? When done manually in main, everything is fine. When trying it through init() nothing happens (Also no error message). The adress is always 0x0, I guess the null pointer.

#define GAMES 100

typedef struct{
  double *scores;
}SCORES;

void init(SCORES *arr);

int main(){
  SCORES *numbers = NULL;
  init(numbers);

  printf("Adress is: %p\n", numbers);      //Still 0x0
  return 0;
}



void init(SCORES *arr){
  arr = (SCORES*) malloc(GAMES * sizeof(SCORES));
}

Trying it with the code below works for malloc. I get an adress but if I use free(), memory is still allocated.


void init(SCORES **arr){
  *arr = (SCORES*) malloc(GAMES * sizeof(SCORES));
}

...

init(&numbers);

...

free(numbers);

Solution

  • In the first code snippet you're passing the value of the numbers variable. In the function you change a local variable, and doing so has no effect on the variable is the calling function.

    In the second snippet you correctly pass the address of numbers so it can be set in the function, and the call to free is also correct. Just don't attempt to use the value of numbers after you free it, otherwise it's undefined behavior.