-2

I'm trying to create a two dimensional array of character in c program as:

char array[1000000][10];

but the program output "Segmentation fault" in the runtime. I tried to create it with 100,000 and it worked, but 1,000,000 didn't work. What is the reason that makes this line of code causes Segmentation fault?

Mahmoud Mubarak
  • 139
  • 1
  • 11
  • 1
    That's almost ten MB, normally a stack is in the single-digit range. Windows, for example, only have 1MB stack by default. – Some programmer dude May 06 '15 at 08:12
  • @m.s.: It is not a duplicate because one is about C and the other about C++. – wilx May 06 '15 at 08:12
  • Many other duplicates though, e.g. http://stackoverflow.com/questions/3144135/why-do-i-get-a-segfault-in-c-from-declaring-a-large-array-on-the-stack – Paul R May 06 '15 at 08:13

2 Answers2

2

It is probably overflowing your operating system's idea of how large a stack can be, assuming it's a local variable inside a function.

That array will require 1000000 * 10 = ~9.5 MB of stack space, which is quite a lot.

Try:

  • Making it static.
  • Using malloc() instead.
  • Modifying OS-level limitations.
  • Making it global. Of course global variables are bad, so this is the worst solution in many cases.
unwind
  • 391,730
  • 64
  • 469
  • 606
0

That is about 10 megabytes. You are probably trying to define the variable as function local variable. Stack is usually not that big. Use dynamically allocated memory instead.

wilx
  • 17,697
  • 6
  • 59
  • 114