Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
889 views
in Technique[技术] by (71.8m points)

c - Segmentation Fault doesn't come up immediately after accessing out-of-bound memory

I wrote this piece of code and was expecting a segmentation fault quicly, but it seems I am allowed to access pieces of memory I shouldn't be able to.

#include<stdio.h>
int main()
{
    int tab[1];
    tab[0]=42;
    int i;
    //Expecting Seg Fault from i==1...
    for(i=0;;i++)
    {
        printf("%d  %d 
", i, tab[i]);
    }
    return 0;
}

I am compiling using:

gcc -Wall -Wextra my_code.c -o segfault && ./segfault

Upon execution, variable i reaches values of order 1000 before I get my Segmentation Fault.

My question is: Why am I able to read tab so far ?

PS: Using #include <stdlib.h> and declaring int * tab = (int*)malloc(sizeof(int)); doesn't change anything...

Thanks, bests.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you're using out-of-bound memory, you'll be facing Undefined behavior. You cannot define something called Undefined behavior.

In your case, it is happening at i = 1000s, in others' case it may very well happen at i=347 or so..

Segmentation fault is the result of accessing memory outside the allowed stack address space of your program. it may run properly and surprise you with apparent proper working if you finish your execution within that memory range. an out-of-bound access may produce vaild memory access till the point you're not crossing the stack memory region.

Consider yourself lucky if you get a segmentation fault, because that tells you, something's wrong. Otherwise, you have no idea of the resulting horror.

Note: as a suggestion, the question title should be changed to .. comes up very late or something simmilar


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...