long size = 10000000;
struct foo *bar[size];
will create a very big array, which may cause stack overflow, and therefore your program receive the SIGSEV.
You should create this array dynamically:
struct foo *bar = malloc(size * sizeof(struct foo *));
Why does the program work normally if these is not any function call in main()
?
The definition of foo
will cause main()
to have a large stack frame at runtime. If you does not call any function in main()
, this large stack frame will not be actually allocated or accessed (the entrance code of main()
only make sure that amounts of memory be reserved by manipulating some registers and memory cells); but if you call a function in main()
, the calling itself will try to access some addresses in that main()
stack frame, because of stack overflow, those addresses may not be valid, this will cause SIGSEV be sent.
If you disassemble and compare the working and not-working versions of this program, this would be obvious. You could also find it out by stepping through the instructions of not-working main()
one by one.
Without function call in main()
:
0x00001ff0 <main+0>: push %ebp
0x00001ff1 <main+1>: mov %esp,%eax
0x00001ff3 <main+3>: mov %esp,%ebp
0x00001ff5 <main+5>: sub $0x2625a10,%esp
0x00001ffb <main+11>: mov %eax,%esp
0x00001ffd <main+13>: leave
0x00001ffe <main+14>: ret
Call exit()
in main()
:
0x00001fe0 <main+0>: push %ebp
0x00001fe1 <main+1>: mov %esp,%ebp
0x00001fe3 <main+3>: sub $0x2625a28,%esp
0x00001fe9 <main+9>: movl $0x0,(%esp) <==== This causes segfault.
0x00001ff0 <main+16>: call 0x3000 <dyld_stub_exit>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…