Dennis
Dennis

Reputation: 25

Is there any underlying reason behind this undefined behaviour?

I just tried this as an experiment to see what values are held in d at each call. I used gcc on an x86-64 machine.

Is there any reason why the old value of d persists after the function returns? From what I understand the call stack frame is popped off once the function returns each time, correct?

#include<stdio.h>

void fun(char ch){
  char d;
  printf("-- %c\n", d);
  d = ch;
}

int main(){
  fun('a');
  fun('b');
  fun('c');
  return 0;
}

OUTPUT:

--
-- a
-- b 

Upvotes: 2

Views: 62

Answers (1)

dbush
dbush

Reputation: 223699

When you return from a function, the memory that was part of the stack frame of the function typically won't be zero'ed out explicitly, as that would just take up unnecessary cycles. So the memory won't be overwritten until it needs to be.

In your main function you call fun multiple times with no other statements in between. That means that nothing in main touches the memory that was used by a prior invocation of fun before calling it again. As a result, the stack frame of the second call happens to coincide with the stack frame of the first call. And because uninitialized local variables don't get a default value, d takes on whatever value happens to be in that memory location, namely what d contained when the last call to the function returned.

If you added a call to another function such as printf in between each call to fun, then that other function call would write its own stack frame on top of the stack frame of the last call to fun so you would see different results in that case.

Upvotes: 3

Related Questions