【问题标题】:segmentation fault (core dumped) pointer struct data type分段错误(核心转储)指针结构数据类型
【发布时间】:2018-01-05 14:36:00
【问题描述】:

我正在尝试使用 C 中的结构创建树

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

struct node{
  int data;
  struct node * next, * left, * right;
};

struct node * createtree(int data){
  struct node * kosong = (struct node*)malloc(sizeof(struct node*));
  kosong->data = data;
  kosong->left = kosong->right = NULL;
  return kosong;
}

void printtree(struct node * tree){
  if(tree == NULL) return;
  printtree(tree->left);
  printf("%d ",tree->data);
  printtree(tree->right);
}

int main(){
  struct node * pohon = NULL;
  pohon = createtree(1);
  pohon->left = createtree(2);
  pohon->right = createtree(3);
  pohon->left->left = createtree(4);
  pohon->left->right = createtree(5);
  printtree(pohon);
}

每当我编译它都会出现分段错误。然后我尝试删除 * next 指针,它编译并成功运行。我知道树不需要 * next 指针,但我不明白为什么它不会因为另一个相同的指针而编译。 感谢您的帮助。

【问题讨论】:

  • struct node * kosong = (struct node*)malloc(sizeof(struct node*)); --> struct node * kosong = malloc(sizeof(struct node));(同样next未初始化。)
  • 1.不正确的格式是 [struct node * = (char *) malloc(size)] 吗?
  • 2.为什么下一个未初始化是原因?
  • bluepixy 提到的格式是正确的。 Don't cast memory allocation functions in C.
  • 我刚刚编译它,我得到了段错误

标签: c++11 pointers struct


【解决方案1】:

为了帮助您理解错误:

  • 函数createtree(int data)的第一行:

    struct node * kosong = (struct node*)malloc(sizeof(struct node*));
    

    应该是

    struct node * kosong = (struct node*)malloc(sizeof(struct node));
    

    因为您正在为结构节点分配内存,而不是为指向结构节点的指针。

这是您的段错误的实际原因。我编译了代码,只修复了这个错误,它工作得非常好。 当然,您应该尝试初始化所有指针和变量,因为不这样做可能会以未定义的行为结束,这可以是任何东西,就像分段错误一样。

【讨论】:

  • 阅读您的评论后,我尝试打印 sizeof(struct node) = 32 和 sizeof(struct node*) = 8 的结果。删除 1 个指针后,sizeof(struct node) 变为 24,它工作得很好。这是否仍然算作未定义的行为,因为我分配的内存少于所需的内存(我分配的指针大小为结构节点)?
  • 正确。由于您分配的内存少于结构所需的内存,因此不知道您是否要覆盖堆中的某些数据,这会导致您的段错误。
猜你喜欢
  • 2020-04-06
  • 1970-01-01
  • 2016-09-07
  • 2021-05-04
  • 2015-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
相关资源
最近更新 更多