You need to allocate new space as well. Consider this code fragment:
char * new_str ;
if((new_str = malloc(strlen(str1)+strlen(str2)+1)) != NULL){
new_str[0] = ''; // ensures the memory is an empty string
strcat(new_str,str1);
strcat(new_str,str2);
} else {
fprintf(STDERR,"malloc failed!
");
// exit?
}
You might want to consider strnlen(3)
which is slightly safer.
Updated, see above. In some versions of the C runtime, the memory returned by malloc
isn't initialized to 0. Setting the first byte of new_str
to zero ensures that it looks like an empty string to strcat.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…