I wrote a quick program which executes every statement before giving a seg fault error.
struct foo
{
int cat;
int * dog;
};
void bar (void * arg)
{
printf("o hello bar\n");
struct foo * food = (struct foo *) arg;
printf("cat meows %i\n", food->cat);
printf("dog barks %i\n", *(food->dog));
}
void main()
{
int cat = 4;
int * dog;
dog = &cat;
printf("cat meows %i\n", cat);
printf("dog barks %i\n", *dog);
struct foo * food;
food->cat = cat;
food->dog = dog;
printf("cat meows %i\n", food->cat);
printf("dog barks %i\n", *(food->dog));
printf("time for foo!\n");
bar(food);
printf("begone!\n");
cat = 5;
printf("cat meows %i\n", cat);
printf("dog barks %i\n", *dog);
// return 0;
}
which gives a result of
cat meows 4
dog barks 4
cat meows 4
dog barks 4
time for foo!
o hello bar
cat meows 4
dog barks 4
begone!
cat meows 5
dog barks 5
Segmentation fault (core dumped)
I’m not really sure why it seg faults at the end? Any comments/insights are deeply appreciated.
You’re dereferencing a pointer to invalid memory,
food.The line:
declares food to be a pointer to a struct foo. But since you’re not initializing the pointer, it’s pointing to an undefined area of memory you don’t own. You can either just allocate on the stack (note I’ve changed the type of food):
or use
malloc(keeping the type as struct foo *):Later you should free it (though in this case it doesn’t matter much):
There are other issues with the program (e.g. the void* parameter), but this addresses the memory violation.