initialize array with stackoverflow error

1

I have simple method:

void loadContent()
{
    int test[500000];
    test[0] = 1;
}

when I call this method, this error occurs:

Unhandled exception at 0x00007FF639E80458 in RasterizeEditor.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x000000AE11EB3000).

I changed the arraysize to 100 and everything is working fine... but I need 500000 integer values, so what should I do? C++ must be able to manage 500000 int values in one array, can the problem be somewhere else? or does I just have to change a setting of visual studio 2015?

c++
arrays
visual-studio-2015
asked on Stack Overflow Apr 11, 2018 by Thomas

2 Answers

1

When you create array like this, it's located into the "stack", but apparently your stack'size isn't sufficient.

You can try to place it into another place, like the "heap" (with dynamic memory allocation like malloc) like:

#include <stdlib.h>
#include <stdio.h>

void loadContent()
{
  int    *test = malloc(sizeof(int) * 500000);

  if (!test) {
     fprintf(stderr, "malloc error\n");
     exit(1);
  }
  test[0] = 1;
}
1

In visual studio you can adjust the stack size your application uses. It is in the project properties under linker system.

In general you don't want to do that as it makes things fragile. Add a few more functions and you need to go back and adjust it again.

It is better to do as suggested and use malloc or better std::vector to get the memory allocated on the heap.

Alternatively if it is safe to do so you can declare your array at the file level outside the function using static or an anonymous namespace to ensure it is private to the file. Safe here means your program only calls the function once at any time.

answered on Stack Overflow Apr 11, 2018 by Stan Blakey

User contributions licensed under CC BY-SA 3.0