C Program crashing with large arrays

前端 未结 4 885
难免孤独
难免孤独 2021-01-17 08:15

I\'m trying to run a simulation that involves a large amount of calculations and values.

I\'ve got an issue in that large arrays cause the program to crash before it

4条回答
  •  情书的邮戳
    2021-01-17 08:45

    It's a stack overflow.

    Bearing in mind that;

    1 byte =    n bits
    1 kb   = 1024 bytes = 2^10 bytes
    1 mb   = 1024 kb    = 2^20 bytes
    1 gb   = 1024 mb    = 2^30 bytes
    1 tb   = 1024 gb    = 2^40 bytes
    

    Assuming the default stack sizes in gcc are (according to this webpage);

    • Linux: 1.8MB | 1,872KB | 1,916,928 bytes

    • Windows: 1MB | 1,024KB | 1,048,576 bytes


    Expanding on rohit's answer (originally i was just going to write a comment, but it's to much writing for a comment and i have a solution at the end), if your array has 3,200,320 bytes | 3,125KB | 3MB

    the size of your stack overflow on each platform would be;

    • Linux: 3,125KB - 1,872KB = 1,253KB | 1,283,072 bytes overflowed.

    • Windows: 3,125KB - 1,024KB = 2,101KB | 2,151,424 bytes overflowed.


    To make gcc compile your program with a larger stack, like 8MB you can do;

    gcc file.c -Wl,--stack,8388608
    

    And the program should not overflow because after the array is put on the stack you are left with:

    • 8,388,608 - 3,200,320 = 5,188,288 bytes | 5,066KB | 4.9MB of stack space.

提交回复
热议问题