0

I need an int array of size 20000000. If I put it in main() it will result in sigsegv. But not if I declare it as a global varialbe. What's the difference?

int a[20000000] = {0};
amazingjxq
  • 4,487
  • 7
  • 33
  • 35
  • 4
    Local variable -> stack allocation, global variable -> heap allocation (but it depends on compiler implementation). – Adriano Repetti Oct 22 '14 at 11:02
  • Local variables inside functions are put on the process stack. The stack is normally in the single-digit megabyte range, on Windows the default stack is a single megabyte. You're trying to create an array containing almost 80 megabytes. – Some programmer dude Oct 22 '14 at 11:02
  • 1
    @AdrianoRepetti: No, not really. global variables are not allocated on the heap and not on the stack. They're allocated from the .bss segment, which is a completely different kind of beast. Note that "stack" "heap" and ".bss" are not termed by the C standard. – datenwolf Oct 22 '14 at 11:03
  • Same issue as the C++ code in http://stackoverflow.com/questions/1847789/segmentation-fault-on-large-array-sizes?rq=1 – nos Oct 22 '14 at 11:03
  • @datenwolf And for initialized variables (like the one in the question) if it was global it would be in the data segment, which also is not specified in the C standard. – Some programmer dude Oct 22 '14 at 11:04
  • @datenwolf yes _heap_ is pretty vague word here (I tried to make it...straight). Global variables are allocated...well...where compiler will think is best according to other conditions (literal? volatile? thread local?). Standard doesn't (because actually it can't) say where. In short: .bss? Maybe yes, maybe not (depends what compiler has to do). – Adriano Repetti Oct 22 '14 at 11:05
  • 1
    @JoachimPileborg: While we're at nickpicking, the variable gets initialized to all elements zero, which by the definition is the behavior for everything in the .bss segment. So the compiler can see, that the explicit initialization just does the same as placing it in bss and may choose to do so. Well actually it's the linker's choice if we get really nitpicky. – datenwolf Oct 22 '14 at 11:05
  • And here is a equivalent question for C: http://stackoverflow.com/questions/571945/getting-a-stack-overflow-exception-when-declaring-a-large-array – zch Oct 22 '14 at 11:05
  • @datenwolf: what does "they are allocated in the .bss segment" mean? The .bss segment is a part of a file. – qdii Oct 22 '14 at 11:08
  • @qdii I think it's a common thinking that global variables are merely dumped/copied from .bss into memory. Actually it's pretty wrong (at least it's just a case, not the rule). One highlighting example: thread locale variables. – Adriano Repetti Oct 22 '14 at 11:10
  • @AdrianoRepetti OK, I think I just misread: he actually wrote they are allocated FROM the .bss segment and I got it – qdii Oct 22 '14 at 11:14
  • @qdii yes but it's still a special case, not the rule. – Adriano Repetti Oct 22 '14 at 11:16

0 Answers0