Why does this code crash?

why does this code crash? uses strcat illegally in character pointers?

 #include <stdio.h> #include <string.h> int main() { char *s1 = "Hello, "; char *s2 = "world!"; char *s3 = strcat(s1, s2); printf("%s",s3); return 0; } 

please provide the correct way to access the array and pointers.

+6
c crash
source share
3 answers

The problem is that s1 points to a string literal, and you are trying to change it by adding s2 to it. You are not allowed to modify string literals. You need to create an array of characters and copy both lines into it, for example:

 char *s1 = "Hello, "; char *s2 = "world!"; char s3[100] = ""; /* note that it must be large enough! */ strcat(s3, s1); strcat(s3, s2); printf("%s", s3); 

โ€œLarge enoughโ€ means at least strlen(s1) + strlen(s2) + 1 . + 1 must take into account the zero limiter.

To be told, you should seriously consider using strncat (or perhaps the best, but non-standard strlcat , if available), which are checked against borders and therefore far outperform strcat .

+11
source share

The correct way in this case would be to allocate enough space in the target string (s1) to save 6 extra characters (s2), as well as a zero delimiter for the string.

 char s1[14] = "Hello, "; char *s2 = "world!"; char *s3 = strcat(s1, s2); printf("%s",s3); 
+2
source share

Here is a quote from the strcat () manual: "The strcat () function adds the src string to the dest string, overwriting the null byte ('\ 0') at the end of dest, and then adds the terminating null byte. The strings cannot overlap, and the dest string must have enough room for the result. "

The problem is that s1 and s2 point to static lines that are read-only, so if you try to perform the strcat operation, with such a line in the dest parameters you get an error message.

The best way to create your hello home string here is malloc so that it can contain both s1 and s2. Also, be sure to add '\ n' at the end of the printf line, otherwise you may be surprised.

Here is the code I would write if I were you:

 int main() { char* s1 = "Hello "; char* s2 = "World !"; char *s3 = malloc((strlen(s1) + strlen(s2) + 1) * sizeof(char)); /* +1 is for the null terminating character and sizeof(*s3) is the actual size of a char. */ if (s3) { strcat(s3, s1); strcat(s3, s2); printf("%s\n", s3); free(s3); // always free what you alloc when you don't need it anymore. } return 0; } 
0
source share

All Articles