-6

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);
alter_igel
  • 6,899
  • 3
  • 21
  • 40
jupiter
  • 23
  • 6
  • 4
    What do you mean by "memory is still allocated"? How do you verify that? – Yksisarvinen Dec 17 '20 at 17:02
  • C (and for this code also C++) uses pass-by-value. So `init(numbers);` is in your case the same as `init(NULL);`. In other words - the function know nothing about `numbers` – Support Ukraine Dec 17 '20 at 17:03
  • 1
    Also, obligatory comment that using `malloc()` without placement `new` is Undefined Behaviour in C++. – Yksisarvinen Dec 17 '20 at 17:05
  • @Yksisarvinen When I use " printf("Size: sizeof(number[0])); " it still says that 16 bytes are allocated to that adress. – jupiter Dec 17 '20 at 17:55

1 Answers1

3

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Thank you for your answer. The problem is, that when I use " printf("Size: %ld", sizeof(*numbers[0])); " I get 16 bytes. So free() does not free anything. – jupiter Dec 17 '20 at 18:03
  • @jupiter That doesn't say that bytes are allocated. The `sizeof` operator gives you the size in bytes of the type of the operand, and is evaluated at compile time. There's no way to verify that `free` worked without using a memory debugging tool like valgrind. – dbush Dec 17 '20 at 18:15
  • This means, theoretically, that I don't need to worry when "sizeof" gives 16 bytes. Thank you. – jupiter Dec 17 '20 at 18:18