Understand how it works to function call and memory stack.
This code works, but it’s wrong. It takes advantage of a behavior that cannot be guaranteed. By pure coincidence the variable str
of show()
was allocated in the same place as the variable str
of set()
. Because of this it works, but if you change this code a little bit the coincidence does not occur and will take a junk of memory. Technically it’s already picking up garbage, but it’s garbage that’s what you wanted, so it seems to be okay.
When the code declares a local variable of a function this is placed in the first possible position of the stack. When it goes back to the calling function, the stack indication backfires indicating that what is there is no longer needed and that any new cell allocation must occur at the previous point. This is useful because it makes memory allocations very fast. When it calls the other function it needs to allocate memory. Where will it allocate? In the same place he had allocated in the other function. Then if you access this variable, it takes the value that was already there, even because C does not erase the memory on its own.
Just change this and you’ll see trouble:
int x = 0;
char vet[12];
printf("vet = '%s'\n", vet);
printf("x = %d", x);
Behold "working" in the ideone. And in the repl it.. Also put on the Github for future reference.
What is being printed ?
– Marco Souza
-> " vet = 'Rat gnawed' "
– FábioArsénio