栈空间大小限制
一. 查看栈大小限制
不同系统的栈空间大小不同,可通过如下方法查看系统栈大小限制
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; }