开发者

Stack overflow when declare 2 array

开发者 https://www.devze.com 2023-02-10 12:08 出处:网络
When I run my program with 1 array, like this: int a[430][430]; int i, j, i_r0, j_r0; double c, param1, param2;

When I run my program with 1 array, like this:

    int a[430][430];
    int i, j, i_r0, j_r0;
    double c, param1, param2;
    int w_far = 0,h_far = 0;
    char* magic_num1 = "";

it's good!

But, when I write:

    int a[430][430];
    int i, j, i_r0, j_r0;
    int nicky[430][430]; // Added line
    double c, param1, param2;
    int w_far = 0,h_far = 开发者_如何学运维0;
    char* magic_num1 = "";

the program not run with the error: "stack overflow"! I don't know how to solve it!


You need to either increase the stack space (how that is done depends on your platform), or you need to allocate the array from the heap, or even better, use std::vector instead of an array.


You're trying to allocate ~1.48 MB of stuff on the stack1, on your system (and not only on it) that's too much.

In general, the stack is not made for keeping big objects, you should put them in the heap instead; use dynamic allocation with new or std::vector, or, even better suited in your case, boost::multi_array.


1. Assuming 32 bit ints.


A proper solution is to use heap, but also note that you'll likely find that changing to:

short a[430][430];
short nicky[430][430]; // Added line

fixes the overflow, depending on your platform. So if 'short', or 'unsigned short' is big enough, this might be an option.

In fact, even when using the heap, consider carefully the array type to reduce memory footprint for a large array.


Local variables are allocated to "stack", which is a storage space used to several purposes and limited to a certain size.

Usually you can declare variables up to several kilobytes, but when you want to use more memory, usually suggested to use "heap", which can be allocated by new operator or std::vector.

std::vector is an alternate for traditional arrays, and its data is safely stored in heap.


To avoid stack overflow, allocate the arrays in the heap.

If one uses C, then allocating an array of size n in the heap can be done by e.g.

int* A = (int*) malloc(n*sizeof(int));

But you must remeber to free that memory when no longer needed with

free(A);

to avoid memory leak.


Equivalently in C++:

int* A = new int[n];

and free with

delete [] A;

This site was helpful.

0

精彩评论

暂无评论...
验证码 换一张
取 消