SuperDisk
SuperDisk

Reputation: 2840

C Dynamic List Troubles

typedef struct {
    long blarg;
} item;

typedef struct 
{
    item* items;
    int size;
} list;

List and Item structs, fairly simple.

list l;
l.size = 3;
realloc(l.items, l.size*sizeof(item));

Create a list, allocate it to hold 3 items.

item thing;
item thing2;
item thing3;

thing.blarg = 1337;
thing2.blarg = 33;
thing3.blarg = 123;

l.items[0] = thing;
l.items[sizeof(item)+1] = thing2;
l.items[(sizeof(item)*2)+1] = thing3;

Create some items and add them to the list... but when printing them:

printf("List 0: %ld\n", l.items[0].blarg);
printf("List 1: %ld\n", l.items[sizeof(item)+1].blarg);
printf("List 2: %ld\n", l.items[(sizeof(item)*2)+1].blarg);

List 0: 1337 
List 1: 33 {
List 2: 1953720652 !

Where did it all go wrong?

Upvotes: 0

Views: 73

Answers (2)

Wuwoo
Wuwoo

Reputation: 106

realloc(l.items, l.size*sizeof(item));

has just alloced l.size (namely 3) item elements, while sizeof(item)+1 and sizeof(item)*2+1 have exceeded the range of l.items array, so the unknown value would be read, and in fact, segment fault should happen

If you want to use l.items in the way you did, you should convert l.items to (void*) first, and then convert it back to item* while getting value of blarg

Upvotes: 0

D.Pham
D.Pham

Reputation: 199

You should change l.items[sizeof(item)+1] and l.items[(sizeof(item)*2)+1] --> l.items[1] and l.items[2]

Upvotes: 1

Related Questions