2011-09-30 197 views
0

在测试程序执行期间,我总是得到一个分段错误。我无法弄清楚为什么。也许有人可以给我解释一下,我确定我把指针混在一起。指向结构和函数指针的指针 - > Seg Fault

#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; 
} 
+0

你还没有初始化test.st_xy – markh44

+0

'RET =的init(test.st_xy);'st_xy是一个指向一个结构,但它从来没有初始化 – stijn

+0

@戴维·赫弗南对不起,我忘了,接受了答案,现在我做到了。 thx的信息链接 – arge

回答

4

您从不分配实际的xy对象。你的test.st_xy只是一个垃圾指针,你不能取消引用。

相反,做这样的事情:

static struct z test; 
static struct xy inner_test; 
test.st_xy = &inner_test; 

// ... 

ret = init(test.st_xy); 
+0

Aaaarhhh,thx很多。我看了几遍代码,但没有认出xy的缺失分配! – arge

+0

@arge如果答案是有用的,那么接受它会很好。 – jrok

2

你传递一个未初始化的指针,以XY的初始化函数。

init(test.st_xy); 

st_xy尚未初始化。我认为不需要st_xy是一个指针。

struct z { 
    struct xy st_xy; 
}; 

int main(int argc, char **argv) 
{ 
    static struct z test; 
    init(&test.st_xy); 
}