I'm pretty new to C, so I apologize if this is pretty standard knowledge..
I have a function like so, where I am appending a bunch of C-style strings together and outputting it:
char *example(int n, int days, int years){
char *ret;
if (n < 5) {
ret = (char*)malloc(sizeof(char)*256);
sprintf(ret, "There are %d days in %d years", days, years);
ret = (char*)malloc(strlen(ret));
return ret;
}
else {
char *s1;
char *s2;
char *s3;
s1 = example(n/2, days, years);
s2 = example(n + 5, days, years);
s3 = example(n--, days, years);
int length = strlen(s1) + strlen(s2) + strlen(s3);
ret = (char*)malloc(length);
strcat(ret, s1);
strcat(ret, s2);
strcat(ret, s3);
return ret;
}
}
This is prefixing each of the new concatenations with a few garbage characters. I'm assuming my issue is in my memory management, but I'm not sure.. Is this simple? What have I done wrong? Also, how can this be done cleaner?