Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Malloc 'ing array of struct in struct

Tags:

arrays

c

struct

I've been doing research for a while, and I'm not finding anything that helps me.

I have the following struct declarations:

typedef struct position_struct{
    int x;
    int y;
} pos;

typedef struct item_struct{
    char member1;
    pos member2;
} item;

typedef struct room_stuct{
    item * member3;
    pos * member4;
    pos member5;
} roomLayout;

And the code to try to malloc it is (I removed the error checking for brevity):

 roomLayout *genFloor () {
                                                         // Allocate mem for Arrays of:
    roomLayout * room = malloc(sizeof(roomLayout) * 6 ); //     6 rooms
    room->member3     = malloc(sizeof(item)       * 10); //     10 member3's
    room->member4     = malloc(sizeof(pos)        * 10); //     10 member4's

    /* TESTING */
    room[0].member3[0].member1 = 'd';
    printf("Room[0] is good\n");
    room[1].member3[0].member1 = 'd';
    printf("Room[1] is good\n");           // Never prints/makes it to this line


    return room;
 }

When I try this, assigning to room[1] causes a crash, but not room[0]. My guess is that I havent actually allocated enough space for the whole array and only one spot. But I don't understand why as I believe that I'm following what I see everywhere else.

If someone could please explain to me the procedure for allocating memory for this kind of setup, that would be very helpful! Thank you.

like image 754
Nawar Ismail Avatar asked Jul 18 '26 01:07

Nawar Ismail


1 Answers

You are only allocating member3 and member4 for the first room; not for all of them. In the line room->member3, room is at the beginning of the memory segment, or at room[0], which allocates space for 10 member3s. room[1], however, has not allocated any space for any member3s (similarly for doors). Work around this by allocating in a loop:

for(i = 0; i < 6; ++i)
{
    room[i].member3 = malloc(sizeof(room[i].member3) * 10);
    room[i].member4 = malloc(sizeof(room[i].member4) * 10);
}

When free-ing the memory, remember to use a similar loop, i.e.

for(i = 0; i < 6; ++i)
{
    free(room[i].member3);
    free(room[i].member4);
}

free(room);
like image 156
R_Kapp Avatar answered Jul 19 '26 16:07

R_Kapp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!