3

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!

2
  • 9
    Lucky for you, this site is specifically concerned with stack overflows ;-) Commented Feb 14, 2011 at 0:38
  • 2
    I find that the program is being particularly helpful; instead of giving incomprehensible error messages, it is just pointing you to where it can get fixed. :) Commented Feb 14, 2011 at 0:49

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.