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

Asked

Viewed 118 times

3

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

What will be the return of this code and why?

I didn’t understand why one function took the value of the other variable.

Follows 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;
}
  • What is being printed ?

  • -> " vet = 'Rat gnawed' "

1 answer

3


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.

  • Got it, thanks bro!

  • 1

    +1 for "but is wrong" =- he is "very wrong" - and if the question fi in an oulista test of exercises, the author should lose his "license to program' for some 12 months for rehabilitation. as an Arduino, or an old APPLE 2,, or even an old PC with up to Windows 98, could lock the machine.

  • 1

    Can you tell your teacher that "people on the Internet" told you not to do this.

  • 1

    @jsbueno would love it if you had a license to program :D

  • 1

    me no, Para mm progrmar is for everyone. But some people should have the same hunt - type - a "negative license" to NOT program.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.