Meghan
Meghan

Reputation: 305

structure and pointers in C

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

Answers (4)

jag
jag

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

jacekmigacz
jacekmigacz

Reputation: 789

change:

next2=malloc(sizeof(entry_t *));

to

next2=malloc(sizeof(entry_t));

Upvotes: 1

Kranthi Kumar
Kranthi Kumar

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

unwind
unwind

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

Related Questions