So I was trying to solve the transforming expressions problem and I wrote this code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getT();
void getExpr(char *e);
char* solve(char *e);
int main()
{
int t = getT();
char *expr = calloc(402, sizeof(char));
int i;
for(i = 0; i < t; i++)
{
getExpr(expr);
char *result = solve(expr);
printf("%s\n", result);
free(result);
}
free(expr);
return 0;
}
int getT()
{
int t;
fscanf(stdin, "%d\n", &t);
return t;
}
void getExpr(char *e)
{
fgets(e, 402, stdin);
}
char* solve(char *e)
{
char *lhs, *rhs;
char *op = calloc(1, sizeof(char));
int i = 1;
if(e[i] != '(')
{
lhs = calloc(1, sizeof(char));
lhs[0] = e[i++];
}
else
{
lhs = solve(&e[i]);
int lb = i++;
while(lb > 0)
{
if(e[i] == '(')
lb++;
else if(e[i] == ')')
lb--;
i++;
}
}
op[0] = e[i++];
if(e[i] != '(')
{
rhs = calloc(1, sizeof(char));
rhs[0] = e[i];
}
else
rhs = solve(&e[i]);
strcat(lhs, rhs);
free(rhs);
strcat(lhs, op);
free(op);
return lhs;
}
On my home computer this works without a hitch. However, on Sphere I get a SIGABRT runtime error. If I remove all of the calls to free(..) I do not get this error and my program is accepted by Sphere. Can anyone explain this? What would be happening differently on Sphere that would cause the free(..) to call abort??
Obviously this ins't that big of an issue since I got the correct answer but I thought I was using *alloc and free correctly. Is this my error or is it the way Sphere runs submitted code??