Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change random memory location on purpose between two executions in c

Tags:

c

memory

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 in this code.

#include <stdio.h>

int main(void){
     int sum;
     sum += 5;
     printf("%d", sum);
     return 0;
}

Sometimes output is 5. To demonstrate the undefined behaviour of not initialising the variable sum to zero I am looking for an example.

like image 569
Felix Yah Batta Man Avatar asked Oct 16 '18 05:10

Felix Yah Batta Man


2 Answers

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.

like image 184
visibleman Avatar answered Oct 07 '22 16:10

visibleman


Memory is usually initialized to zero when a process is started. Otherwise, you would get old memory contents from another process, which would be a security risk. Because of this, code like this will, in my experience, usually print zero:

#include <stdio.h>

int main(void) {
    int x;
    printf("%d\n", x);
}

You have a greater chance to get non-zero results if you use memory that has been used by your own process. For example, I just got non-zero printouts with this program:

#include <stdio.h>

void f(void) {
    int x;
    printf("%d\n", x);
}

int main(void) {
    f();
    f();
    f();
}

But remember that according to the standard, the contents of an uninitialized local variable (with storage class auto) is undefined, so a compiler is allowed to always set its variables to zero. Or -4.

like image 3
Thomas Padron-McCarthy Avatar answered Oct 07 '22 17:10

Thomas Padron-McCarthy