Dataflashsabot
Dataflashsabot

Reputation: 1509

Why is this giving me a segfault?

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?

Upvotes: 0

Views: 204

Answers (4)

sbi
sbi

Reputation: 224009

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.

Upvotes: 2

Kiril Kirov
Kiril Kirov

Reputation: 38143

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

Upvotes: 1

fredoverflow
fredoverflow

Reputation: 263058

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.

Upvotes: 4

Twig
Twig

Reputation: 611

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

Upvotes: 1

Related Questions