printf command causing a seg fault? [duplicate]

2019-07-18 04:52发布

问题:

This question already has an answer here:

  • Getting a stack overflow exception when declaring a large array 9 answers

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.