-3

I made a mistake and used uninitialized local variable in a function and happened to find a single line of "cout" could change the uninitialized value. To simplify, I show the problem as follow.

#include <stdio.h>

void foo(void){
  int i;
  printf("%d\n", i);
  i = 777;
}
int main(void){
  foo();
  //cout << "hello!" << endl;
  foo();
  return 0;
}

The line I comment out will change the output from (unknown#;777) to (unknown#;hello!;0). Could someone help explain? Thanks.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490

1 Answers1

0

This is because of stack behavior.

The first case:

int main(void){
  foo();
  foo();
  return 0;
}

The first foo() builds the stack and initialize the location of i with 777 and leave it as is. Then, the second call to foo() lays on the same stack structure where location of i is still 777. So, in this case printf prints 777.

The second case:

cout << "hello!" << endl is actually calling two functions:

cout.operator<<("hello!");
cout.operator<<(endl);

Which overwrites our previously created stack structure.

frogatto
  • 28,539
  • 11
  • 83
  • 129