【问题标题】:Calloc error on struct pointer of pointer指针的结构指针上的Calloc错误
【发布时间】:2021-03-17 00:14:52
【问题描述】:

我的 calloc 有问题,但我不知道为什么。这是我的代码:

void ens_init(ensemble* node, ullong value, uint i){
  // *node = malloc(sizeof(struct ensemble)); # Doesn't work
  // *node = calloc(1, sizeof(struct ensemble)); # Doesn't work
  node = calloc(1, sizeof(struct ensemble));
  if (*node == NULL){
    printf("Caloc error\n");
    exit(-1);
  }
  (*node)->key = value;
  (*node)->index = i;
  (*node)->left = NULL;
  (*node)->right = NULL;
}

这是我的整体结构:

typedef unsigned int uint;
typedef unsigned long long int ullong;

struct ensemble{
  ullong key;
  uint index;
  struct ensemble* left;
  struct ensemble* right;
};
typedef struct ensemble* ensemble;

在研究非确定性有限自动化(法语中的 NFA 或 AFN)时,这就是我使用这种结构的原因。我的老师想编写一个确定 NFA 的函数,在这个函数中我们必须使用树。

这是我如何调用这个函数来测试它

int main(int argc, char *argv[]){
  ensemble B = NULL;

  ens_ajouter(&B, 5, 1);

  return 0;
}

感谢您的帮助:)

【问题讨论】:

  • 两条 cmets 行中的任何一条都是正确的。未注释的不是。您需要定义“不起作用”的含义,并且您需要使用显示问题的minimal reproducible example 更新您的问题。

标签: c struct segmentation-fault calloc nfa


【解决方案1】:

您尝试在调用初始化函数ens_init() 之前调用函数ens_ajouter()。这意味着函数calloc() 永远不会从main() 函数中调用。

我认为你在隐藏ensemble 类型是struct ensemble指针这一事实是错误的。这会使您的代码不可读。

我建议您将 typedef 更改为:

typedef struct ensemble ensemble;

或者,更好的是,根本不使用 typedef。有这样的代码就很好了:

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

typedef unsigned int uint;
typedef unsigned long long int ullong;

struct ensemble {
    ullong key;
    uint index;
    struct ensemble* left;
    struct ensemble* right;
};

void ens_init(struct ensemble** node, ullong value, uint i) {
    *node = calloc(1, sizeof(struct ensemble));
    if (*node == NULL){
        printf("Calloc error\n");
        exit(-1);
    }
    (*node)->key = value;
    (*node)->index = i;
    (*node)->left = NULL;
    (*node)->right = NULL;
}

int main(void) {
    struct ensemble B;
    struct ensemble* pointer_to_B;
    pointer_to_B = &B;
    ens_init(&pointer_to_B, 5, 1);

    return 0;
}

为什么?因为它可以让你看到你的分配调用中存在很大的问题。在ens_init() 中,您分配了一个足够大的内存区域以容纳struct ensemble,然后将该区域的地址存储在指向结构指针的指针中(而不是指向结构的指针)。而且您甚至没有在main() 函数中创建struct ensemble 类型的局部变量(我已修复)。你应该改写这个(注意星号):

void ens_init(struct ensemble** node, ullong value, uint i) {
    // Asterisk added:
    *node = calloc(1, sizeof(struct ensemble));
    if (*node == NULL){
        printf("Calloc error\n");
        exit(-1);
    }
    (*node)->key = value;
    (*node)->index = i;
    (*node)->left = NULL;
    (*node)->right = NULL;
}

我很奇怪,你到处都有指向结构的指针。如果没有必要,你应该避免这种情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 2016-03-21
    • 2012-03-28
    • 2015-07-10
    • 1970-01-01
    相关资源
    最近更新 更多