2

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?

Jens
  • 69,818
  • 15
  • 125
  • 179
user2445465
  • 107
  • 1
  • 1
  • 2

2 Answers2

3

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];
Nicholaz
  • 1,419
  • 9
  • 11
  • 2
    Usually static storage class allocations are OK, too. And why not just allocate a 2D array instead of doing the access multiplication gymnastics yourself? – Carl Norum Jun 02 '13 at 16:55
  • 1
    +1. Alternatively, `char (*f)[10000] = malloc(sizeof(*f) * 10000)` would also avoid the stack overflow while still allowing `f` to be indexed as a 2-dimension array. Making `f` static may have unattractive side-effects - a 100Mb executable to be mapped into memory. – simonc Jun 02 '13 at 16:56
  • 1
    @simonc, making `f` static will probably have no effect on executable size - it would be zero-initialized. – Carl Norum Jun 02 '13 at 17:00
  • Thanks Carl, my mistake. Unfortunately I noticed just too late to correct my comment. – simonc Jun 02 '13 at 17:03
  • No problem - just wanted to clarify. – Carl Norum Jun 02 '13 at 17:08
  • 3
    ... and to take it to the extreme, you can allocate it as `char (*f)[10000][10000] = malloc(sizeof *f)`. Just keep in mind that in this case you'll have to access it as `(*f)[i][j]` :)) – AnT stands with Russia Jun 02 '13 at 17:09
  • 1
    LOL ... just occurred to me, that this question is the epitome of this site, a stack overflow :-) – Nicholaz Jun 02 '13 at 17:15
0

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.

Jens
  • 69,818
  • 15
  • 125
  • 179