Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Weird & interesting program output

Tags:

c

memory

I've written the following code in C:

 #include <stdio.h>
 #include <stdlib.h>

 #define LEN 100 

 int main(void) 
 {
    int arr[LEN];
    int i;

    for (i = 0; i < LEN; i++)
       printf("%d ", arr[LEN]);

    getchar();
    return 0;
 }

First, notice I'm deliberately accessing memory which isn't part of the array (the last cell will be in index LEN-1 and I'm accessing arr[LEN], not arr[i].

The weird result is that when I run the program, it prints all the numbers between 0 to... LEN-1. For exmaple, when LEN defined to be 100 like here, the output is:

0 1 2 ..... 99

Please run the program. Does it happens to you too? I think this is platform-dependant behavior. (If it is relevant, I ran this code on Windows 7.)

Why does the value of arr[LEN] change?

like image 329
Programmer Avatar asked Jan 15 '14 14:01

Programmer


2 Answers

The stack is where local variables are kept. Your compiler is using the memory location after the array (arr[LEN] basically) to keep i. Therefore you are accidentally printing out i on each iteration. A different compiler might keep i somewhere else and you wouldn't see the same thing.

like image 54
Kate Gregory Avatar answered Oct 18 '22 18:10

Kate Gregory


To expand on the answers of others, consider the following:

Code

#include <stdio.h>
#include <stdlib.h>

#define LEN 100 

int main(void) 
{
    int i;
    int arr[LEN];

    printf("&arr[LEN]: %p\n", &arr[LEN]);
    printf("&i:        %p\n", &i);

    return 0;
}

Output

&arr[LEN]: 0x7fff5cf90a74  
&i:        0x7fff5cf90a74

On my machine, if i is declared before arr, i and arr[LEN] have the same address.

Run the following on your machine

#include <stdio.h>
#include <stdlib.h>

#define LEN 100 

int main(void) 
{
    int arr[LEN];
    int i;

    printf("&arr[LEN]: %p\n", &arr[LEN]);
    printf("&i:        %p\n", &i);

    return 0;
}

You should see something very similar (addresses different, of course) to what I saw.

like image 28
Fiddling Bits Avatar answered Oct 18 '22 17:10

Fiddling Bits