Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: sprintf and recursion

In C, is it possible to use recursion within the sprintf function ? For some reason I get a segmentation fault when I do it:

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;
}
like image 251
Suugaku Avatar asked May 11 '10 18:05

Suugaku


1 Answers

You're getting segment because out is not initialized, not because of the recursion. You should allocate some memory for it, e.g.

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;
}
like image 123
kennytm Avatar answered Sep 30 '22 19:09

kennytm