Home > OS >  Why there is a pattern on the garbage values in the C program?
Why there is a pattern on the garbage values in the C program?

Time:03-11

I try this program in CS50 Week 4 memory. I noticed there is a pattern on the garbage values. Initially, I thought garbage values should be randomize. But, it looks like there is different pattern depended on the number of garbage value requested.

Code:

#include <stdio.h>
#include <stdlib.h>
int main (void)
{
    //Create an array of 3
    int scores[3];

    //Print 3 random garbage values
    //scores[0] have big random values
    //scores[1] have 3276X
    //scores[2] have 0
    for (int i = 0; i < 3; i  )
    {
        printf("%i\n", scores[i]);
    }
}

Result:

pset4/W4.1/ $ ./garbage
-1498813296
32767
0
pset4/W4.1/ $ ./garbage
-1011161520
32764
0
pset4/W4.1/ $ ./garbage
1340521040
32765
0
pset4/W4.1/ $ ./garbage
1244491248
32765
0
pset4/W4.1/ $ ./garbage
-1200874656
32764
0

Can anyone help to explain what is happening here? Thanks!

CodePudding user response:

Assuming x86_64, when you declare an array like that, the compiler simply makes room on the stack, something like:

sub $12, %rsp (12 bytes for 3 integers)

Then when you access the array you're actually looking at the stack. I know you have a 64 bit OS because if you take scores[0] scores[1] << 32 you get something similar to 0x0000 7FFC 4A2D 6DF0 and it just so happens that the stack starts around 0x0000 7FFF FFFF FFFF and growing down. So what your looking at is a pointer on the stack (probably a return address from a previous call) and you know that the bottom 32 bits of the next values on the stack is 0, maybe a local variable of the function, who knows.

The important part is that the stack won't change that much (especially in the 32 upper bits) and this is why you're noticing this pattern of 32 764 (0x7FFC).

Read more: https://en.wikipedia.org/wiki/X86_calling_conventions

  • Related