【问题标题】:Segmentation fault on initializing pointer (malloc) in different function [duplicate]在不同函数中初始化指针(malloc)时出现分段错误[重复]
【发布时间】:2013-02-23 15:51:48
【问题描述】:

我正在尝试通过这样做来初始化一棵树:

typedef struct {
    char *value;
    struct children_list *children;
} tree;

typedef struct t_children_list {
    tree *child;
    struct t_children_list *next;
} children_list;

void initializeTree(tree *root, char *input)
{
  if((root = malloc(sizeof(tree))) == NULL) { abort(); }
  root->value = input;
}

void main()
{
  // Create the tree
  char *input = "aaaaaa";
  tree *my_tree = NULL;

  initializeTree(my_tree, input);
}

但是我遇到了分段错误。为什么会这样?我正在传递一个指向函数的指针,并在其中保留内存。有错吗?

【问题讨论】:

标签: c tree malloc


【解决方案1】:

指针 'my_tree' 是按值传递的(这是在 C 中完成的唯一方法)

所以 my_tree 基本上是复制的,并且没有分配 'root' 对 'my_tree' 变量有任何影响。

您想要返回一个指针,因此将一个指针传递给一个指针 (**),然后初始化 *root 以实际修改我的树

void initializeTree(tree **pRoot, char *input)
{
  if((*pRoot = malloc(sizeof(tree))) == NULL) { abort(); }
  *pRroot->value = input;
}

void main()
{
  // Create the tree
  char *input = "aaaaaa";
  tree *my_tree = NULL;

  initializeTree(&my_tree, input);
}

或者根本不通过它而是返回它:

tree *initializeTree(char *input)
{
  tree *root = NULL;
  if((root = malloc(sizeof(tree))) == NULL) { abort(); }
  root->value = input;
  return root;
}

void main()
{
  // Create the tree
  char *input = "aaaaaa";
  tree *my_tree = initializeTree(input);
}

【讨论】:

  • Byval 传递不仅是默认值,也是 C 语言中传递参数的唯一方式。
  • 你是对的。 & 参数中的东西是 C++ .. 我会编辑我的答案
猜你喜欢
  • 1970-01-01
  • 2019-04-23
  • 1970-01-01
  • 1970-01-01
  • 2019-09-02
  • 2014-12-31
  • 2013-07-26
  • 1970-01-01
  • 2019-03-27
相关资源
最近更新 更多