Warm tip: This article is reproduced from serverfault.com, please click

Expected or unexpected Segmentation errors?

发布于 2020-12-02 14:46:33

I am working on code security. So the code discussed below is known to be vulnerable.

I want to understand why running the code below has no segmentation error

#include <stdio.h>

int main(){
    int a[3]={0,1,2};
    for (int i=0; i<=400; i++)
      printf("value of a[%d] is %d\n",i, a[i]);      

}

but running the code below, with the loop bound changed to 4000 from 400, has a segmentation error? I would like to know why there is the segmentation error in one case but not in the other.

#include <stdio.h>

int main(){
    int a[3]={0,1,2};
    for (int i=0; i<=4000; i++)
      printf("value of a[%d] is %d\n",i, a[i]);      

}
Questioner
zell
Viewed
0
Eliyahu Machluf 2020-12-02 23:01:35

As mentioned, when you access out of bound memory, you invoke undefined behavior. Undefined behavior at your case may crash the program (as with the 4,000 value) and may print arbitrary values (as with the 400 value).

I assume that when tried to print the array of 4,000 integers, you reached memory which should not be used for data (e.g. program text segment), while when you used the array of 400 integers, you were still at the stack area (or heap,bss segment or data segement) of your program.

Here is process structure as described at https://en.wikipedia.org/wiki/Code_segment

here is process structure as described at https://en.wikipedia.org/wiki/Code_segment