Home  >  Q&A  >  body text

c++ - 数组声明在main函数中运行时栈溢出?

环境是win10+VS2015
int common_subsequence[1000][1000]声明在mian函数中,运行到这步栈溢出;
int common_subsequence[100][100]声明在main函数中,不会发生栈溢出;
int common_subsequence[1000][1000]声明为全局,不会发生栈溢出。
究竟怎么回事?有什么建议吗

天蓬老师天蓬老师2764 days ago944

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 15:34:07

    The default stack size under windows is 1mb, 4*1000*1000 is about 4mb, so calling main will cause stack overflow.

    common_subsequence is an automatic variable, and the memory allocation of the object will be completed before the function starts, which means that the overflow occurs before the first line of code of the main function is executed.

    It is recommended to use dynamic memory allocation + smart pointers, or use container classes directly.

    std::unique_ptr<int [][1000]> sequence(new int[1000][1000]);
    std::vector<std::vector<int> > sequence;

    reply
    0
  • Cancelreply