printf command causing a seg fault? [duplicate]

我的梦境 提交于 2019-12-12 18:00:46

问题


When I try to initialize a large double dimensional character array, it works perfectly fine. But when I add a simple print command, it gives me a segmentation fault. Any ideas as to why this is happening?

#include<stdio.h>
int main(void)
{
    printf("!");  
    char f[10000][10000];
}

It works fine without the printf command, or even if the printf command prints nothing, (i.e. ""). If I make it print anything at all it gives the error.

Any help?


回答1:


This is probably because you are exceeding the stack. Your definition of f takes 100MB Stack space (10000x10000 bytes) and probably as soon as you actually use the stack, the system will find that there isn't that much room on the stack and segfault. You'll probably find the same with calling any other function.

Allocations of that size should be done through malloc().

   char *f= malloc(10000*10000);

   // access two dimensionally (equivalent of f[5][8])
   char z= f[5*10000 + 8];



回答2:


You are exceeding an unspecified limit of your C implementation, in particular, the total size of objects with automatic storage duration (aka "local variables"). The size of f[] is 100.000.000 bytes. Many C implementation keep automatic variables on the stack, which usually is a limited resource. On my Unix system (FreeBSD) I can inspect this limit:

$ ulimit -a
-t: cpu time (seconds)              unlimited
-f: file size (blocks)              unlimited
-d: data seg size (kbytes)          33554432
-s: stack size (kbytes)             524288
[...]

and if higher powers allow, increase it with ulimit -s number.



来源:https://stackoverflow.com/questions/16885016/printf-command-causing-a-seg-fault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!