what is causing Unhandled exception at memory : Stack overflow

0

I'm new to C++ and I'm implementing the Canny edge detector algorithm by myself. for that, I've declared some 2D arrays. it gives me the error " Unhandled exception at 0x000A1809 in ConsoleApplication3.exe: 0xC00000FD: Stack overflow (parameters: 0x00000000, 0x00E92000)"

I minimized the number of elements of my arrays, and it worked. but when I need arrays with more elements

//2.Gradian Calculation: a.Calculating Gx and Gy   b.Calculation sqrt(Gx^2 + Gy^2)   c.Calculating the gradiant orientation
int Fx[3][3] = { {-1,0,1},{-2,0,2},{-1,0,1} };
int Fy[3][3] = { {1,2,1},{0,0,0},{-1,-2,-1} };
int image[100][100] = { 50 };
int gradian_x[100][100] = { 0 };
int gradian_y[100][100] = { 0 };
double edgeStrength[100][100] = { 0 };

//Calculating Gx
for (int i = 1; i < 99; i++)
{
    for (int j = 1; j < 99; j++)
    {
        gradian_x[j][i] = image[j - 1][i - 1] * Fx[0][0] + image[j][i - 1] * Fx[1][0] + image[j + 1][i - 1] * Fx[2][0] + image[j + 1][i + 1] * Fx[2][2] + image[j][i + 1] * Fx[1][2] + image[j - 1][i + 1] * Fx[0][2];

    }
}
c++
stack-overflow
asked on Stack Overflow Oct 17, 2019 by M.H.Muhamadi • edited Oct 17, 2019 by Jabberwocky

1 Answer

0

Stack space is limited. Provided that int is 4 bytes on your platform and double is 8 bytes, you ask for 195 kiB memory, which may or may not be available in stack (that's ignoring any other necessary things from stack like function calls etc).

For storing larger sets of data, you should use dynamic memory allocation with std::vector (it uses heap memory instead of stack memory, which is much larger than stack):

const int initialValue = 50;
std::vector<std::vector<int>> image (100, std::vector<int>(100, initial_value);

Note that int image[100][100] = { 50 }; will initialize only image[0][0] to 50 and the rest of the e lements to 0. It is fixed in above example (all elements are initialized with 50 there), but if you want to retain that behaviour, you should make initial_value to be equal to 0 and change image[0][0] directly.


For increased performance, you should preferable use a specialized library like Eigen. If you don't want external resources, you may want to use std::vector<std::array<int, 100>> instead, which will allocate memory in single block (better for processor cache):

std::array<int, 100> initialArray;
std::fill(initialArray.begin(), initialArray.end(), 50);
std::vector<std::array<int, 100>> image (100, initialArray);
answered on Stack Overflow Oct 17, 2019 by Yksisarvinen • edited Oct 17, 2019 by Yksisarvinen

User contributions licensed under CC BY-SA 3.0