Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does using strcat on character pointers crash? [duplicate]

Tags:

c

crash

why does this code crash? is using strcat illegal on 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 give a proper way with referring to both array and pointers.

like image 784
Ashish Yadav Avatar asked Mar 13 '10 05:03

Ashish Yadav


1 Answers

The problem is that s1 points to a string literal and you are trying to modify it by appending s2 to it. You are not allowed to modify string literals. You need to create a character array and copy both strings into it, like so:

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. The + 1 is to account for the null terminator.

That having been said, you should seriously consider using strncat (or the arguably better but nonstandard strlcat, if it is available), which are bounds-checked, and thus are far superior to strcat.

like image 103
James McNellis Avatar answered Sep 19 '22 23:09

James McNellis