Larry
Larry

Reputation: 1765

c - Passing a structure variable to a function : segfault

Context

Here is my code

typedef struct {
    int m;
    int (*v)(int *restrict a);
} polo;

int toto(int *restrict a){
    printf("hello %d\n",*a);
}
int main()
{

    polo *kilo;
    kilo->m = 84;
    kilo->v = toto;

    kilo->v(&kilo->m);

    return 0;

}

Problem

Segfault. I cannot get why. The same code works if kilo is not a pointer anymore. (polo kilo; kilo.m=...).

Could you explain me please ?

Thanks

Upvotes: 1

Views: 834

Answers (5)

Sathish
Sathish

Reputation: 3870

You need to allocate the memory for Pointer kilo.

int main()
{

polo *kilo;
kilo = malloc(sizfof(polo)); 
kilo->m = 84;
kilo->v = toto;

kilo->v(&kilo->m);
free(kilo);
return 0;

}

Without allocation of memory for Structure pointer you can't store the value's in structure member.

But When you declare polo kilo;, it doesn't need memory allocation. Because you are declared a structure variable. when you are declaring structure variable, the memory os allocated for it statically. so it will work!

Upvotes: 1

Jakub
Jakub

Reputation: 573

polo *kilo; - the kilo pointer to polo is defined, but points anywhere.

kilo->m = 84 - you attemt to write 84 to a random address. SEGFAULT.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409482

The value of an uninitialized local (non-static) variable is indeterminate, using such a variable (except for initialization) leads to undefined behavior which can lead to crashes.

The problem here is that you declare kilo to be a pointer, but you don't make it point anywhere. In fact, there's really no use to make it a pointer in the first case, just declare it as a normal non-pointer variable:

polo kilo;
kilo.m = 84;
kilo.v = &toto;

kilo.v(&kilo.m);

Tip of the day: Avoid using pointers as much as you can, they are a great source of problems unless care is taken.

Upvotes: 0

askmish
askmish

Reputation: 6684

You should allocate memory before using a pointer.

You can do this:

polo *kilo = malloc(sizeof(polo));

or

polo temp;
polo *kilo = &temp;

And then the rest of the code will work fine.

Upvotes: 1

David Ranieri
David Ranieri

Reputation: 41055

You need to reserve space for kilo:

polo *kilo = malloc(sizeof(*kilo));

or

polo *kilo = malloc(sizeof(polo));

Don't forget to call free(kilo); at the end.

Upvotes: 4

Related Questions