c++pointersstructbus-error

Bus error when setting array element in struct


I have the following struct:

struct State {
    int num_walls;
    Wall walls[];

    int num_persons;
    Person persons[];
};

I want to have persons contain two Persons and walls contain one Wall:

int num_walls = 1;
int num_preson = 2;

State simState = *(State*)malloc( sizeof(simState) + num_person*sizeof(Person) + num_walls*sizeof(Wall));
simState.num_walls = num_walls;
simState.num_persons = num_person;
simState.walls[0] = w;
simState.persons[0] = p1;
simState.persons[1] = p2;

When I do that I get Bus error (core dumped). When I only set the persons, everything works fine. I.e. this works:

int num_walls = 0;
int num_preson = 2;

State simState = *(State*)malloc( sizeof(simState) + num_person*sizeof(Person) + num_walls*sizeof(Wall));
simState.num_walls = num_walls;
simState.num_persons = num_person;
// simState.walls[0] = w;
simState.persons[0] = p1;
simState.persons[1] = p2;

The code is c++11 and I'm using gcc (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609

Why does that happen?


Solution

  • So this is legal C++, it may be what you are trying to achieve

    struct State {
        int num_walls;
        Wall* walls;
        int num_persons;
        Person* persons;
    };
    
    State simState;
    simState.num_walls = num_walls;
    simState.walls = new Wall[num_walls];
    simState.num_persons = num_person;
    simState.persons = new Person[num_person];
    simState.walls[0] = w;
    simState.persons[0] = p1;
    simState.persons[1] = p2;
    

    It's not good C++, but at least it's legal.

    The important points (in either language) is that you do not have to allocate simState, it gets it's memory just by being declared, but you do have to allocate your two variable length arrays simState.persons and simState.walls