分配具有函数指针作为字段的结构

Allocating a struct having function pointers as fields

我试图在 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 && 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分配内存。这就是 Valgrind 所抱怨的。由于您没有充分分配并分配给成员指针,因此导致 undefined behaviour.

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

或者,更好:

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

应该可以解决您的问题。