I found on the internet a fine string concatenating function and tried to rewrite its else scope with use of realloc as it was written with use of calloc. However, I failed. Most of the time I tried to use my version of this function the STM32 microcontroller reached HardFault_Handler. With the original code that uses calloc I had no problem like this.
I tried to find what was wrong using debugger built int STM32CubeIDE but to no avail. I don’t know if I have some memory leak or if I calculate byte sizes or lengths incorrectly. Every help and suggestion is deeply appreciated. Thank You in advance!
void concatenateStrings(char **string, const char *stringToAdd) {
// Reset *str
if ( *string!=NULL && stringToAdd==NULL ) {
free(*string);
*string=NULL;
return;
}
// Initial copy
if (*string==NULL) {
*string=calloc( strlen(stringToAdd)+1, sizeof(char) );
memcpy( *string, stringToAdd, strlen(stringToAdd) );
}
else { // Append
//WORKING
char *tmp=NULL;
uint16_t stringSize=strlen(*string);
uint16_t stringToAddSize=strlen(stringToAdd);
tmp=calloc( stringSize+1, sizeof(char) );
memcpy( tmp, *string, stringSize );
*string=calloc( stringSize+stringToAddSize+1, sizeof(char) );
memcpy( *string, tmp, strlen(tmp) );
memcpy( *string + stringSize, stringToAdd, stringToAddSize );
free(tmp);
//NOT WORKING
/* char *tmp=NULL;
uint16_t stringSize=strlen(*string);
uint16_t stringToAddSize=strlen(stringToAdd);
tmp=realloc(*string, (stringSize+stringToAddSize+1)*sizeof(char));
//memset(tmp+stringSize, 0, (stringSize+stringToAddSize+1)*sizeof(char)-stringSize*sizeof(char));
*string=tmp;
memcpy(*string + stringSize, stringToAdd, stringToAddSize+1);*/
}
}