C Program crashing with large arrays

前端 未结 4 764
难免孤独
难免孤独 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:29

    2*4*5*10001 = 400,040 elements. Double means 8 bytes per element. And 400,040 * 8 = 3,200,320 bytes

    3,200,320 bytes size is beyond the stack memory size to handle.

    0 讨论(0)
  • 2021-01-17 08:34

    adsorption is being allocated on the stack, and it must be overflowing the stack. Hence the error.

    Use malloc and family to allocate large chunks of data on the heap.

    edit

    Or make it static -- @Matt McNabb thanks! :-)

    0 讨论(0)
  • 2021-01-17 08:36

    Local variables implicitely have automatic storage duration, so they are effectively placed in space-limited stack. Either declare you array with static qualifier, move it into global scope, outside any function (so now implicitely it has static storage duration, which variables are placed on data segment, note static in this context means something totally different, so don't be "explicit to much" there), or use malloc or calloc functions from <stdlib.h> header to allocate it on heap (especially useful if size of array indices is known run-time).

    Note that C99 also features variable-length arrays (VLA), where size of indices is determined run-time, however these are only limited to automatic storage duration.

    0 讨论(0)
  • 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.
    0 讨论(0)
提交回复
热议问题