initialize array with stackoverflow error [duplicate]

我与影子孤独终老i 提交于 2021-02-17 03:30:17

问题


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?


回答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;
}



回答2:


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.



来源:https://stackoverflow.com/questions/49770696/initialize-array-with-stackoverflow-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!