一. 查看棧大小限制
不同系統的棧空間大小不同,可通過如下方法查看系統棧大小限制
cat /proc/1/limits
該文件列出了系統資源限制情況(ubuntu 16.04):
Limit Soft Limit Hard Limit Units Max cpu time unlimited unlimited seconds Max file size unlimited unlimited bytes Max data size unlimited unlimited bytes Max stack size 8388608 unlimited bytes Max core file size 0 unlimited bytes Max resident set unlimited unlimited bytes Max processes 7770 7770 processes Max open files 1048576 1048576 files Max locked memory 65536 65536 bytes Max address space unlimited unlimited bytes Max file locks unlimited unlimited locks Max pending signals 7770 7770 signals Max msgqueue size 819200 819200 bytes Max nice priority 0 0 Max realtime priority 0 0 Max realtime timeout unlimited unlimited us
可知該系統中棧空間大小限制為8M。
二. 超過棧大小后段錯誤
#include <stdio.h> int main(void) { char buf[8*1024*1024] = {0}; printf("%c\n", buf[1024*1024]); return 0; }
Segmentation fault (core dumped)
三. 解決方案
對於超出棧大小的內存申請采用malloc或直接定義為全局變量。
#include <stdio.h> #include <string.h> char buf[10*1024*1024]; int main(void) { memset(buf, 'c', sizeof(buf)); printf("%c\n", buf[1024*1024]); return 0; }