0
void init(int *a) {
    int *b = malloc(sizeof(int));
    *b = 4;
    a = b;
    printf("b address %d\n", b);
    printf("a address %d\n", a);
    printf("%d\n",*a);
}

int main()
{
    int *a = malloc(sizeof(int));
    printf("a address %d\n", a);
    init(a);
    printf("a address %d", a);

    return 0;
}

will print the output

a address 32206864
b address 32211008
a address 32211008
4
a address 32206864

Here, the init function is initializing the value for a. However, this is done is incorrect and I am trying to determine why. Observe that once the init function ends the pointer a forgets the address it's supposed to point to. I assume this has something to do with the fact that a is set to b, a pointer that gets popped off the stack once the function ends.

But why does this make sense? Shouldn't a remember what memory address it's been set to? After all, the scope of a is the main function, not the init function.

Ryan
  • 113
  • 6
  • 1
    As a side note, you must use `%p` to print a pointer. – Ken Y-N Sep 27 '19 at 00:38
  • 1
    @KenY-N: As a side side note, the C standard is voluntary and does not say that anybody **must** do anything. In this regard, the C standard only says it does not define the behavior when you pass a pointer for `%d`. It does not say you must not do it. That is not a useful distinction in this particular case, but it is an important philosophy to understand because the region between what the C standard defines and what you **can** do is where implementation-specific extensions to C are implemented. – Eric Postpischil Sep 27 '19 at 00:55

1 Answers1

1

The a in the function init and the a in main are different objects. The call init(a) only passes the value of a to the function. That value is only a copy of the value in the a in main. The init function does not receive any reference to the a in main.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • I see. It's obvious once you point it out, but I was confused at first because I tend to think of functions as machines that modify inputs to produce outputs, but in reality they modify copies of the inputs. This answer also makes me realize why it's better practice to run pointers as parameters instead of the structs they point to. (Saves time copying the parameters) – Ryan Sep 27 '19 at 00:53