Reputation: 2820
I have the following struct in C.
struct a {
long state;
long uid;
long w, x, y, z, xx, yy, zz, xxx, yyy, zzz;
char comm[64];
};
Then I do a malloc
as follows.
buf = malloc (100 * sizeof(struct a));
But when I try to access the individual structs as follows, I get a seg fault.
for (i = 0; i < 100; ++i) {
tmp = buf + (i * sizeof(struct a));
printf ("\t>%d>%ld,%ld\n", i, tmp->state, tmp->uid);
}
I am getting a seg fault after the first 10 entries. I have no idea why this happens. Please help.
Upvotes: 0
Views: 74
Reputation: 37930
The compiler already handles sizeof()
advancement during pointer arithmetic. Thus,
ptr + i;
is the same as
&ptr[i];
It is wrong to use
ptr + (i * sizeof(some_type));
Upvotes: 3
Reputation: 18492
This line is wrong:
tmp = buf + (i * sizeof(struct a));
You don't need to multiply i
by the size of each element in the array, this is done implicitly for you based on the type of buf
.
What you're actually doing is
tmp = &buf[i * sizeof(struct a)];
when what you're really trying to do is
tmp = &buf[i];
Upvotes: 4
Reputation: 9579
if buf is a pointer to a struct a, the pointer math should be:
tmp = buf + i;
Upvotes: 5