【问题标题】:Pointer to struct & function pointers -> Seg Fault指向结构和函数指针的指针-> Segfault
【发布时间】:2011-09-30 09:01:26
【问题描述】:

在执行此测试程序期间,我总是遇到分段错误。我不知道为什么。也许有人可以向我解释一下,我确定我把指针的东西弄混了。

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

【问题讨论】:

  • 你还没有初始化test.st_xy
  • ret = init(test.st_xy); st_xy 是一个指向结构体的指针,但它从未被初始化
  • @David Heffernan 对不起,我忘了接受答案,现在我做到了。感谢信息链接

标签: c++ c


【解决方案1】:

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

相反,请执行以下操作:

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

 // ...

 ret = init(test.st_xy);

【讨论】:

  • 啊啊啊啊,非常感谢。看了好几遍代码都没有认出xy的缺失分配!
  • @arge 如果答案是有帮助的,我会很高兴接受它。
【解决方案2】:

您将指向 xy 的未初始化指针传递给 init 函数。

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    相关资源
    最近更新 更多