linux:
如果是gcc/linux的可执行文件,先用readelf看:
$ readelf -l /bin/ls
…
Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align
…
GNU_STACK 0x000000 0x00000000 0x00000000 0x00000 0x00000 RW 0x4
…
复制代码
如果MemSiz为零,则由OS决定栈的大小。
$ ulimit -a | grep stack
stack size (kbytes, -s) 8192
复制代码
可以看到OS设定的值是8MB
编译时改变stack大小的方法:
ld –stack=栈尺寸
或
gcc -Wl,–stack=栈尺寸
例如 gcc -Wl,–stack=0x4000000
struct rlimit lim;
if(getrlimit(RLIMIT_STACK, &lim) < 0)
{
perror(“getrlimit”);
exit(1);
}
printf(“stack size:%lu\n”,lim.rlim_cur);
windows:
如果是VC++ 用dumpbin看。
dumpbin /HEADER c:\windows\system32\attrib.exe
…
OPTIONAL HEADER VALUES
…
80000 size of stack reserve
2000 size of stack commit
100000 size of heap reserve
1000 size of heap commit
…
复制代码
可见VC++给的默认栈空间比较少,VC++v10.0给得要大点。
100000 size of stack reserve
1000 size of stack commit
100000 size of heap reserve
1000 size of heap commit
复制代码
如果这样就会栈溢出
void foo(void)
{
char stackoverf[0x100000+4];
memset(stackoverf, 0xcc, sizeof stackoverf);
}
复制代码
编译链接时指定栈空间大小
CL /F stack_size
或者
LINK /STACK:stack_size