llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

'Segmentation fault: 11' in the special index for an array

Open haoxintu opened this issue 6 years ago • 4 comments

Bugzilla Link 44975
Resolution INVALID
Resolved on Feb 20, 2020 12:04
Version 6.0
OS Linux
CC @topperc,@zygoloid

Extended Description

Hi, I am developing a random c generation tool to find c compiler bugs.

I found an interesting code that compiles successfully but get a "Segmentation fault:11" result when executing it.

The c code is

void foo(int* a ) { a[8]=1; } int main (int argc, char* argv[]) { int array[] = {0}; foo(array); return 0; }

My compile command is "clang-6.0 test.cc" and it succeeds. Then I execute it using "./a.out" but I got a "Segmentation fault:11" error.

I know we should initialize an array before using it. But the most interesting thing is that only an index of 8 in a array can trigger the error, other index is fine for execution.

I test the code in clang-3.8, clang-6.0, clang-7 in ubuntu16.04 and got the same error.

haoxintu avatar Feb 20 '20 16:02 haoxintu

The array in main is implicitly an array of 1 int (the bound is deduced from the length of the initializer), so the access in foo is out of bounds, and hence has undefined behavior. The fact that this sometimes crashes and sometimes does not is not a compiler bug.

I'm not sure why we chose 32 bytes there. You're compiling without optimizations so we probably did something simple. How much space gets allocated is not subject to any standard so its possible gcc uses a different amount.

topperc avatar Feb 20 '20 18:02 topperc

I see. The bytes when allocating a stack is fixed? I mean when I run this code in GCC, the index of 6 is the trigging one.

haoxintu avatar Feb 20 '20 17:02 haoxintu

The generated code allocates 32 bytes on the stack and the array is located at the that location. So the stack looks like this

                   esp - 32 return address to go back to caller of main
                   esp - 24 unitialized
                   esp - 16 unitialized
                   esp - 8  unitialized

array starts heres -> esp unitialized

Since an access to array[8] is equivalent adding array + 8 * sizeof(int). The store to array[8] clobbers the return address. So when main tries to return it goes to a bad location. This is why it only crashes with 8. Other values don't alias to the return address.

topperc avatar Feb 20 '20 17:02 topperc