Change random memory location on purpose between two executions in c

  • A+

I sometimes want to show my students that local variables have to be initialized before use. But on some occasions they get the initial value of zero without being initialized. So my students don't believe me. For example sometimes in this code.

#include <stdio.h>  int main(void){      int sum;      sum += 5;      printf("%d", sum); } 

Sometimes output is 5. But I want to show you have to write sum=0 before using it.


Pointing to standards is good. But I understand your desire to show an example to your students. I'm not sure about the best way; but to increase your chances of seeing the undefined behavior, you can declare multiple variables that cannot easily be optimized away by the compiler.

#include <stdio.h> void main(){     int sum1;     int sum2;     int sum3;     int sum4;     int sum5;     int sum6;     int sum7;     int sum8;     int sum9;     int sum=sum1+sum2+sum3+sum4+sum5+sum6+sum7+sum8+sum9;     printf("%d/n",sum); } 

On my system; recent Ubuntu, with recent GCC this produces incorrect results on every run, whereas your original example always produced 5. But I can't make any guarantees for your system.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: