【问题标题】:storing a structure object at void pointer在 void 指针处存储结构对象
【发布时间】:2016-05-13 20:35:40
【问题描述】:

假设我有以下代码:

struct inst {
    uint32_t field1;
    uint16_t field2;
   void *priv;
};

struct ops {
    int (*init)(void);
    int (*deinit)(void);
    int (*run)(void);
};

所以我可以这样做:

struct inst p1;
struct ops ops;

/* init p1 and ops.*/
...

inst->priv = ops;

以后这样访问priv中的数据安全吗:

return (struct ops *)inst->priv

【问题讨论】:

    标签: c function pointers


    【解决方案1】:
    inst->priv = ops;
    

    不应该

    inst->priv = &ops;
    

    另外,为了回答您的问题,“以后以这种方式访问​​数据是否安全:”,不,不是。这取决于您在哪里创建结构实例。如果你是这样创作的

    struct ops * dummyA()
    {
        struct inst p1;
        struct ops ops;
        //(...)
        inst->priv = (void*)&ops;
        //(...)
        return (struct ops *)inst->priv;
    }
    

    这是不安全的,因为这些结构是在函数内部的堆栈中创建的,因此,当您离开函数时,它们的内存地址将被标记为空闲。

    解决此问题的一种方法是使用堆 (malloc) 或(也许更简单的方法)声明如下结构:

    static struct inst p1;
    static struct ops ops;
    

    这样您就不必担心内存分配问题,并且您可以确定这些堆栈元素在程序结束之前永远不会被擦除,因此您可以随意使用它们的指针。

    【讨论】:

    • 感谢您的反馈。我知道返回堆栈分配对象的问题,我的问题是关于return (struct ops *)inst->priv 中的类型转换——它是必需的,还是可以省略?
    • 但不返回堆栈指针。它不会做你打算做的事情。
    猜你喜欢
    • 1970-01-01
    • 2016-03-21
    • 2014-10-01
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 2019-02-03
    • 2023-03-26
    • 2015-01-04
    相关资源
    最近更新 更多