Reputation: 305
seg fault again!! Please see this and correct me
typedef struct entry_s
{
int key;
int value;
struct entry_s *next1;
} entry_t;
entry_t *next2;
next2=malloc(sizeof(entry_t));
next2->key=key; // this is giving seg fault now...
Thanks
Upvotes: 0
Views: 119
Reputation: 918
The alloction size is wrong: sizeof(entry_t *) is teh size of a pointer, not the size of the ponted value (the structure). When you are accessing the next1 field of the structure, you are reading data right after the place you have allocated.
I would recommand to use the idiomatic pointer initialization form:
next2=malloc(sizeof(*next2));
It allows to change the pointed type without impact on allocation statement:
You should also test the next2 pointer righ after to check if the allocation worked well.
Additionnaly, you are testing a value which have not been initialized (next2->next1). The value of the field is unpredictable just after allocation. The most probable here is that the next1 pointer should be initilized to NULL as no memory has been allocated to store an other "struct entry_s".
Upvotes: 0
Reputation: 789
change:
next2=malloc(sizeof(entry_t *));
to
next2=malloc(sizeof(entry_t));
Upvotes: 1
Reputation: 1264
sizeof(entry_t *) gives you 4 bytes which is nothing but a size of pointer. You need to change your malloc statement to this:
next2=malloc(sizeof(entry_t ));
After malloc add the following statement.
memset(next2, 0x00, sizeof(entry_t))
now you will not get segfault.
Upvotes: 2
Reputation: 400059
It's wrong as written, since there's nothing assigning a valid pointer value to next2
, so you can't de-reference it: it doesn't point at a valid entry_t
.
If you had some initialization, like:
const entry_t *next2 = get_entry_with_key(4711);
if(next2 != NULL)
{
printf("got an entry with %d", next2->key);
if(next2->next != NULL)
printf(" and the next one has %d\n", next2->next1->key);
}
then it would be perfectly fine.
Upvotes: 2