3

重複の可能性:
配列の終わりを超えて書き込むと、セグメンテーション違反が発生しないのはなぜですか?

このコードは、エラーなしでコンパイルおよび実行されます。しかし、どのように?

#include <stdio.h>

int main (void)
{
    int foo[2];

    foo[8] = 4; /* How could this happen? */

    printf("%d\n", foo[8]);

    return 0;
}

ArchLinuxx86_64でGCC4.7.2をコンパイルしています。

gcc -Wall -o "main" "main.c"
4

3 に答える 3

5

Because undefined behavior doesn't mean "you will receive a segfault", that would be defined behavior.

Let's assume you're running in debug mode and your compiler is padding your stack/local variable space. You're probably just writing into some unused part of the stack space.

Build a release version on a Monday when your compiler is feeling cranky and now you overwrite the return address, or the code that sets up the call to printf, whatever. Oops.

Just one possible outcome, but you get the idea.

于 2012-11-04T17:56:44.240 に答える
1

foo[8] may be allocated for your program (padding purpose, for instance), belong to your operating system. With an undefined behavior, anything can happen; you are unlucky, because it works.

于 2012-11-04T17:56:36.507 に答える
0

Try

foo[1000000]=42; 

and see what happens.

于 2012-11-04T17:56:51.190 に答える