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;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With