Reputation: 635
I always get a segmentation fault during execution of this test program. I can't figure out why. Maybe someone could explain it to me please, i'm sure i mixed up the pointer stuff.
#include <stdio.h>
struct xy {
int (*read)();
void (*write)(int);
};
struct z {
struct xy *st_xy;
};
static void write_val(int val)
{
printf("write %d\n", val);
}
static int read_val()
{
/* return something just for testing */
return 100;
}
int init(struct xy *cfg)
{
cfg->read = read_val;
cfg->write = write_val;
return 0;
}
int reset(struct z *st_z)
{
/* write something just for testing */
st_z->st_xy->write(111);
return 55;
}
int main(int argc, char **argv)
{
static struct z test;
int ret;
int ret2;
ret = init(test.st_xy);
printf("init returned with %d\n", ret);
ret2 = reset(&test);
printf("reset returned with %d\n", ret2);
return 0;
}
Upvotes: 0
Views: 624
Reputation: 18905
You pass an uninitialized pointer to xy to the init function.
init(test.st_xy);
st_xy has not been initialized. I think there is no need for st_xy to be a pointer.
struct z {
struct xy st_xy;
};
int main(int argc, char **argv)
{
static struct z test;
init(&test.st_xy);
}
Upvotes: 2
Reputation: 477110
You never allocate the actual xy
object. Your test.st_xy
is just a garbage pointer that you're not allowed to dereference.
Instead, do something like this:
static struct z test;
static struct xy inner_test;
test.st_xy = &inner_test;
// ...
ret = init(test.st_xy);
Upvotes: 4