I just realized a major flaw in the program I was writing. It's a program that symbolically differentiates math functions, e.g. "x^2+5"
--> "2*x"
, and the master function involved starts off like
char * deriveFromTree ( node * rt )
{
char * dfdx = malloc(100*sizeof(char)); // buffer
if (rt->op) // if rt is of the form rt = gx op hx
{
char * dgdx = deriveFromTree(rt->gx); // g'(x)
char * dhdx = deriveFromTree(rt->hx); // h'(x)
char thisop = *rt->op;
if (thisop == '+' || thisop == '-')
{
// ADDITION/SUBTRACTION RULE:
// dfdx = dgdx + thisop + dhdx
dfdx = strcat(dfdx, dgdx);
dfdx = strcat(dfdx, charToString(thisop));
dfdx = strcat(dfdx, dhdx);
}
The problem, as you might already see, is that the result of deriveFromTree
fits in a buffer of length 100
, but the result also be composed of several other results, which just won't work. An alternative solution is getting rid of the buffer and setting dfdx
to be the exact length it needs to be:
char * deriveFromTree ( node * rt )
{
char * dfdx;
if (rt->op) // if rt is of the form rt = gx op hx
{
char * dgdx = deriveFromTree(rt->gx); // g'(x)
char * dhdx = deriveFromTree(rt->hx); // h'(x)
char thisop = *rt->op;
if (thisop == '+' || thisop == '-')
{
// ADDITION/SUBTRACTION RULE:
// dfdx = dgdx + thisop + dhdx
dfdx = malloc(strlen(dgdx) + strlen(dhdx) + 2);
dfdx = strcat(dfdx, dgdx);
dfdx = strcat(dfdx, charToString(thisop));
dfdx = strcat(dfdx, dhdx);
}
But that is inefficient because of the calls strlen(dgdx)
and strlen(dhdx)
iterate through the strings dgdx
and dhdx
and then they are iterated through again in the strcat
calls.
What is the best solution to this problem?
Since you have tagged the question as c++, I would suggest chuck char * and use std::string. The code would look like this: