0

I'm using Microsoft Visual C++ 2008 Express, and have a pretty annoying problem. It doesn't seem to happen in XP but in Vista I can't find a way around it. Whenever I declare variables non-dynamically, if their combined size exceeds about 30mb, the program will crash immediately at start-up. I know that Vista limits non-Win32 apps to 32mb of memory, but I don't think that's my issue. I'm using the Microsoft compiler, and it happens regardless if it's a win32 console app or a win32 window app. I just declare like...

int foo[1000][1000]

...or any combination of variables resulting in a similar size anywhere, and that's good-bye-application. Funny thing is, about 25 % of the times it runs even though this error exists. Am I missing some fundamental programming thingy here? Is static allocation obsolete? Am I going to have to redo the entire application to make use of dynamic allocation?

4

3 回答 3

3

静态分配过时了吗?

你不是在做静态分配——你是在做自动分配,正如其他人所说,你的堆栈用完了。

在 C++ 中,为数据保留空间的常用方法基本上有以下三种:

  1. 在堆栈上 - 这些被称为“自动变量”,它们就是普通的函数局部变量。假设您的“int foo[][]”是 main() 的本地对象,那么这就是它。自动数据受可用堆栈大小的限制,但分配速度非常快(基本上为零时间)。

  2. 静态 - 这些是函数局部变量或类变量,它们以“静态”一词开头,或者它们是在函数或类范围之外定义的变量。静态数据由编译器保留 没有分配时间开销,但内存是为应用程序的整个运行时保留的。

  3. 在堆上 - 这些分配有“new”或“malloc”或某种在内部进行这些调用的机制。分配和释放相比前两个慢,但是你可以有系统给你多少内存,用完可以归还。

这三个有细微的变化 - 例如 alloca 是 1 和 3 的混合体,但这些是基础。

于 2008-12-04T20:10:42.243 回答
1

There might be a stack size setting you need to set that is defaulting to something small. It has been a long time since I needed to play with those settings.

In the link options most likely

I only have MSDEV 2005 at work, but here is what it says about the stack linker option:

The /STACK option sets the size of the stack in bytes. This option is only for use when building an .exe file.

This option specifies the total stack allocation in virtual memory. The default stack size is 1 MB. The linker rounds up the specified value to the nearest 4 bytes.

EDIT

Unless you are doing your own memory management I can't see why you would allocate this statically. But even in that case I would dynamically allocate memory up front...

于 2008-12-04T19:44:55.387 回答
0

The problem is that non-dynamically allocated variables in methods are allocated on the stack, and the maximum stack size is MUCH less than the total available memory. I think it's around 30MB in Windows, yes. What you have done here is, ironically, this very site's namesake. A Stack Overflow.

Edit: According to http://www.cs.nyu.edu/exact/core/doc/stackOverflow.txt ,Window's maximum stack size is 32MB.

于 2008-12-04T19:46:12.683 回答