views:

105

answers:

4

This:

bool grid[1280][1024];
for (int x = 0; x<1280; x++)
{
    for (int y = 0; y<1024; y++)
    {
        grid[x][y] = false;
    }
}

works fine, but

bool grid[1280][1024];
bool grid2[1280][1024];

for (int x = 0; x<1280; x++)
{
    for (int y = 0; y<1024; y++)
    {
        grid[x][y] = false;
        grid2[x][y] = false;
    }
}

gives me a segfault. Why?

+1  A: 

Works fine for me, no segfaults on either using g++ 4.2.1, have you tried these examples alone?

Twig
Yep, making a new console application causes the same thing. I get the Windows 7 'this application has stopped working' box. Using the debugger alerts me to a 'Segmentation Fault'.
Dataflashsabot
I've just tried it on Visual Studio 2008 on server 2003 and i too get that error, can i recomend cygwin, so you can use g++
Twig
+5  A: 

Probably not enough stack space, your second example also crashes on my PC. Try allocating on the heap, or even better, use a proper container class:

#include <array>
#include <vector>

typedef std::array<bool, 1280> line;

int main()
{
    std::vector<line> grid(1024);
    std::vector<line> grid2(1024);

    // no initialization to false necessary
}

Note how I switched the width and the height. You probably want your elements aligned this way to ensure fast linear access.

FredOverflow
Yep, allocating on the heap worked. Thanks!
Dataflashsabot
@Data: You can edit your question and include the new code as well to have it discussed, if you want.
FredOverflow
+2  A: 

I think sizeof(bool) is defined as being the same as sizeof(char). Assuming a char takes one byte on the system you're on, that second example attempts to allocate 2*1280*1024 bytes on the stack. That's 2.5MB. Your system might not provide that much stack space.

Use one of the contaienrs from the standard library which use heap space to store their data.

sbi
@Joe: That was my internal default locale kicking in. Thanks for fixing it!
sbi
+1  A: 

Probably stack overflow. Create the array dynamically, it will work (because it will be created on the heap). Or, use std::vector< std::vector< char > >, instead. ( be very careful, if you decide to use std::vector< bool >.. unless you don't know what exactly you're doing (it's not normal STL container, containing just bools), use it with char ).

Using std::vector< std::vector< char > > will let you use the object as normal two-dimensional array.


EDIT:
std::vector< bool >: "This specialization is provided to optimize for space allocation: In this template specialization, each element occupies only one bit (which is eight times less than the smallest type in C++: char).

The references to elements of a bool vector returned by the vector members are not references to bool objects, but a special member type which is a reference to a single bit, defined inside the vector class specialization as". CPlusPlus

Kiril Kirov