Zhinkk Zhinkk - 4 years ago 93
C Question

Why does one way of malloc seg fault but another doesn't?

If I have an int array:

int *array;

array = malloc(5 * sizeof(int));

and I malloc to it as above, I can then access it and set values to it. Everything is fine.

But if I create that int pointer and pass to it a function and malloc inside the function, I can't access/set values to the array unless I pass it to the array as a pointer to a pointer?

some_void_function(int *array) {
array = malloc(5 * sizeof(int))

int *array;

*(array + 3) = 5; // DOES NOT WORK

To fix it I can make the array accept (int **array) as a parameter and pass in the address of the pointer (so a pointer to a pointer), dereference it, and assign it with malloc:

some_void_function(int **array) {
*array = malloc(5 * sizeof(int))

int *array;

*(array + 3) = 5; // WORKS

Could someone explain this to me? Am I not doing the same thing in both situations? Pass the address and then just dereferencing it is the same thing as just pass in the single pointer in the first place right?

Answer Source

Pointers are variables that hold addresses. But they are subject to the same rules as all other types of variables, meaning they are passed by value.

void some_void_function(int *array) {
    array = malloc(5 * sizeof(int))

array is local to some_void_function, and any change you make to its value isn't reflected in the pointer it was copied from.

To modify variables (pointers included) in the calling code, you have two options:

  1. Pass by pointer, which means a pointer to your pointer:

    void some_void_function(int **array) {
      *array = malloc(5 * sizeof(int))
  2. Return the address you allocated and assign it to the pointer:

    int* some_allocating_function() {
      return malloc(5 * sizeof(int))
    int *array = some_allocating_function();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download