C: sprintf and recursion

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

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;
}
+5
source share
3 answers

You get a segment because it is outnot initialized, not because of recursion. You must allocate some memory for it, for example.

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;
}
+10
source

You have not allocated any memory for out, so you are writing to an arbitrary memory location. This algorithm seems a little unstable on this front - how do you know how much space is allocated for out- do you know any size restrictions on the tree?

+6

undefined. :

char * out;
sprintf(out, "%s:%.2f", node->name, node->distance);

, , undefined, , , .

If you ask if I can use sprintf in a recursive function to add information to the buffer, the answer is perhaps, but not so simple. You will need to maintain a buffer with each recursive call, as well as an index to the buffer that will be updated with each call.

+3
source

All Articles