A variable without assigning value accesses the value of variable in another function

3

I have a Programming Language activity to do, whose code is done in C language, and in this question, the question is:

  

What will be the return of this code and why?

I did not understand why one function got the value of the variable from the other.

Follow the code:

#include <stdlib.h>
#include <stdio.h>

void set() {
char str[12] = "O rato roeu";
}

void show() {
char vet[12];
printf("vet = '%s'\n", vet);
}

int main() {
set();
show();
return 0;
}
    
asked by anonymous 09.06.2016 / 17:22

1 answer

3

Understand how memory stack and function calls stack .

This code works, but it is wrong. He takes advantage of behavior that can not be guaranteed. By pure coincidence the variable str of show() was allocated in the same place of the variable str of set() . Because of this it works, but if you change this code a little, the coincidence does not occur and it will get a memory garbage. Technically it's already getting crap, but it's crap that's what I wanted, so everything seems ok.

When the code declares a local variable of a function this is placed in the first possible position of the stack. When you return to the calling function, the battery indication rewinds indicating that what is there is no longer needed and that any further allocation to the battery must occur at the previous point. This is useful because it makes memory allocations very fast. When you call the other function it needs to allocate memory. Where will you allocate? In the same place that I had allocated in the other function. So if you access this variable, get the value that was already there, because C does not erase memory on its own.

Just change this and you'll see problems:

int x = 0;
char vet[12];
printf("vet = '%s'\n", vet);
printf("x = %d", x);

See "working" on ideone and on CodingGround a>.

    
09.06.2016 / 17:39