Paris P
Paris P

Reputation: 355

C++ Program crashes with array of structs declaration

I can't figure out what's the problem with the following code, it just crashes without outputing anything to the screen:

#include <cstdlib>
#include <iostream>
using namespace std;

typedef struct {
    unsigned int recid;
    unsigned int num;
    char str[120];
    bool valid;
} record_t;

typedef struct {
    unsigned int blockid;
    unsigned int nreserved; 
    record_t entries[100];
    bool valid;
    unsigned char misc;
} block_t;

int main(){
    cout << "Before Buffer" << endl;
    block_t buffer[1000];
    cout << "After Buffer" << endl;
    return 0;
}

I tried Qt debugger and GBD and they just show segmentation fault and point at the start of the main function.

The size of each block_t element is 13,2 Kbs so the size of the buffer array should be around 13Mb. Maybe that's too much for a C-array?

Upvotes: 1

Views: 1055

Answers (2)

Michael Burr
Michael Burr

Reputation: 340168

Your buffer variable is about 13MB - too large for a stack allocation.

Upvotes: 2

taocp
taocp

Reputation: 23624

block_t buffer[1000];

probably used all your stack space (requires larger than 1000* 100 *120 *1 Byte assume ASCII approximately equals 12MB, not considering other fields of those structs), therefore, you get a segmentation fault.

Try to use:

block_t * buffer = new block_t[1000];

or std::vector instead or increase your stack space to larger size if possible.

Upvotes: 3

Related Questions