【问题标题】:Allocating a struct having function pointers as fields分配具有函数指针作为字段的结构
【发布时间】:2021-02-10 00:41:35
【问题描述】:

我试图在 C 中分配一个将函数指针作为字段的结构,但是,valgrind 为以下代码抛出错误“大小为 8 的无效写入”。但是,当int n=1 更改为int n=10 时,代码不会产生错误(分配方式超过必要的内存时不会产生错误)。

#include <stdio.h>
#include <stdlib.h>

struct list {
    int (*one)(int,int);
    int (*two)(int,int);
};

int one0(int x,int y){return x+y;}
int two0(int x,int y){return x-y;}

void assignFunctions(struct list * l){
    l->one = one0;
    l->two = two0;
}

int main(){
    int n = 1;
    struct list * l = calloc(n, sizeof(struct list *));
    assignFunctions(l);
    free(l);
    return 0;
}

这可能是什么问题?编译: gcc -O0 -g a.c &amp;&amp; valgrind --tool=memcheck --leak-check=yes --show-reachable=yes --num-callers=20 --track-fds=yes ./a.out 请记住,这不是真正的代码,它是我必须处理的代码的简化。而且assignFunction(struct list *l)struct list {}的代码不能更改。那么,我真正的问题是如何分配这个结构?

【问题讨论】:

  • 您想为struct list 分配足够的空间,但您只为指向struct list 的指针分配了足够的空间。结构成员的详细信息在这里并不重要。

标签: c linux struct dynamic-memory-allocation


【解决方案1】:

您已为struct list * 分配内存。但真正想要的是为struct list 分配内存。这就是 Valgrind 所抱怨的。由于您没有充分分配并分配给成员指针,这将导致undefined behaviour

struct list *l = calloc(n, sizeof(struct list));

或者,更好:

struct list *l = calloc(n, sizeof *l);

应该可以解决您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 2013-01-05
    • 2013-08-17
    • 2014-01-10
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    相关资源
    最近更新 更多