Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Visual Studio stack overflow with 2D array

I'm using Visual Studio 2010 Win 8. I have a class where I'm making a 2D array to hold game data for a game.

Create a blank console app and make main.cpp and add this code. Using 360 for MAP_SIZE causes stack overflow using 359 doesn't. Why would this be? I'm looking to have a much larger size array. I'd like something like 2000 - 10,000 ideally.

#define MAP_SIZE 360

typedef unsigned short ushort;
typedef unsigned long ulong;

struct Tile
{
    ushort baseLayerTileID;
    ulong ownerID;
};

class Server
{
private:
    Tile _map[MAP_SIZE][MAP_SIZE];
};


int main()
{
    Server s;

    return 0;
}
like image 391
user441521 Avatar asked Dec 20 '12 18:12

user441521


1 Answers

My estimates put sizeof(Tile) at 8 or more. That means sizeof(Server) is at least 360*360*8 = 1036800, which is 0.99 MB. The stack is usually small, and 1MB is a common default size. You should allocate the tiles on the heap instead, perhaps using std::vector.

class Server
{
public:
    Server() : _map(MAP_SIZE * MAP_SIZE) {}
private:
    std::vector<Tile> _map; // position [i][j] is at [i*MAP_SIZE+j]
};
like image 76
R. Martinho Fernandes Avatar answered Sep 18 '22 19:09

R. Martinho Fernandes