Skip to main content
GameDev.net gamedev.net
🔒 Locked

nooby problem with array declaration inside class

Started by Dancho Aug 4, 2008 at 6:01 AM 6 replies 1.1k views
Original Post
Dancho
Dancho
so I have this simple code ( just to demonstrate problem )

#include <iostream>
using namespace std;

class HeightMap
{
	static const int width=1024;
	static const int height=1024;
public:
	char map[width][height];
};

int main()
{
	HeightMap hm;

	return 0;
}

and it compiles without errors with Visual C++ 2005 EE ( debug and release version ) but it crashes when I try to start debug version , but release version starts normally. On the other hand latest Code::Blocks 8.02 also compile fine and runs debug&release version without crashes. If someone could explain this I would be very grateful. thx
ToohrVyk
ToohrVyk
There is a limit to how much data can be allocated on the stack. This limit is OS- and compiler-dependent. In your situation, you're allocating one megabyte of data, which may cause problems. Consider allocating it on the free store instead:

std::auto_ptr<HeightMap> hm(new HeightMap);
Dancho
Dancho
@ToohrVyk
thx for explanation...
Antheus
Antheus
1) Stack size usually defaults to 1Mb. You're exceeded that size. While it's possible to increase stack size, a better solution here is to dynamically allocate the height map.

2) Rather than using static const int, consider templates for this:
template < unsigned int W, unsigned int H >class HeightMap{public:  unsigned int width()  const { return W; }  unsigned int height() const { return H; }  char map[W][H];};...HeightMap<1024, 1024> hm;


In second case, the stack size issue still applies.
Dancho
Dancho
@Antheus
thx,

I also think that dynamic allocation is right way to do this,but
I was just wondering why release version runs and debug crash and
why MinGW works where VC++ doesnt...
ToohrVyk
ToohrVyk
Quote:
Original post by Dancho
I was just wondering why release version runs and debug crash

It's possible that the release version notices the variable is never used and thus completely skips its initialization.

Quote:
and why MinGW works where VC++ doesnt...
The two may be requiring different amounts of memory for the stack.

Dancho
Dancho
hm,
the debug version works when I declare HeightMap object as global,
like this :

#include <iostream>using namespace std;class HeightMap{	static const int width=1024;	static const int height=1024;public:	char map[width][height];};HeightMap hm;int main(){	return 0;}


well,dont know what to think now :)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.