when i try to run this program, i get the error malloc(): memory corruption. The error doesn't come directly from this function, it happens when i try to malloc() after this function. If i remove the line free(ch) it works correctly so i guess the corruption happens when i try to free it. The main() is an example of how i would use the function.
char * makeInt(int val){
char *res = malloc(5);
char l [5] = "";
sprintf(l,"%d",val);
if(val < 10){
strcat(res,"000");
strcat(res,l);
}
else if(val < 100){
strcat(res,"00");
strcat(res,l);
}
else if(val < 1000){
strcat(res,"0");
strcat(res,l);
}
else if( val < 10000){
strcat(res,l);
}
res[4] = '\0';
return res;
}
char * makeString(char *ch){
int t = strlen(ch);
char *chaine = malloc(t+4);
char *nb = makeInt(t);
strcat(chaine,nb);
strcat(chaine,ch);
chaine[t+4] = '\0';
free(ch);
return chaine;
}
int main(){
char *path = malloc(100);
// here we do many operations on path, when i call makeString, path contains something
path = makeString(path);
}
EDIT: Sorry it was late when i posted and i forgot some informations. I added makeInt().About include, i have them in my code but i don't think a missed include would cause a memory corruption since it compiles. Also when i call makeString(), path contains a string. I use makeString() at differents location in the code. When i added free(ch) error appeared, but i don't understand why freeing the memory allocated in the main would cause a memory corruption.
the posted code contains certain logic errors, for instance:
but the initial string MUST have a NUL byte, otherwise it is unknown what value would be returned (I.E. undefined behavior)
The returned value from
malloc()
may or may not have a NUL byte in the first character.This is probably why the posted code is causing a seg fault event.
(you could fix this specific problem by using
calloc()
rather thanmalloc()
ALSO, the parameter to
makeString()
is not initialized to any specific NUL terminated character string. SO it is undefined behavior to pass that parameter tostrlen()
(because the first NUL byte encountered could well be beyond the end of the 'path array)
some suggestions:
here is a version of the code that might work for you.
and the output is: