C:sprintf和递归

Suu*_*aku 5 c recursion printf segmentation-fault

在C中,是否可以在sprintf函数中使用递归?出于某种原因,当我这样做时,我遇到了分段错误:

inline char *TreeNode_toString(const TreeNode *node)
{
  char *out;

  if(TreeNode_isExternal(node)) // If the node has no children...
  {
    sprintf(out, "%s:%.2f", node->name, node->distance);
  }
  else // The node is strictly binary, so it will have two non-null children
  {
    char *l = TreeNode_toString(node->l); // l = left child
    char *r = TreeNode_toString(node->r); // r = right child
    sprintf(out, "(%s,%s):%.2f", l, r, node->distance);
  }

  return out;
}
Run Code Online (Sandbox Code Playgroud)

ken*_*ytm 10

您正在获取段,因为out未初始化,而不是因为递归.你应该为它分配一些内存,例如

inline char *TreeNode_toString(const TreeNode *node)
{
  char *out = malloc(4096);  // <-- allocate

  ...

    char *l = TreeNode_toString(node->l);
    char *r = TreeNode_toString(node->r);
    snprintf(out, 4096, "(%s,%s):%.2f", l, r, node->distance);
    // ^-- please use snprintf to avoid buffer overflow, thanks.
    free(l);    // <-- remember to free
    free(r);    // <-- remember to free
  }

  return out;
}
Run Code Online (Sandbox Code Playgroud)


Car*_*rum 6

您没有为其分配任何内存out,因此您正在写入随机内存位置.这个算法在前面看起来有点不稳定 - 你怎么知道要分配多少空间out- 你知道树上有一些大小的界限吗?