Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

strcat

Status
Not open for further replies.

brent123

MIS
Mar 21, 2006
29
US
I'm new to C and I'm having trouble with strcat. Can someone tell me why I get a segmentationFault error for the below code.

Thanks

Code:
char *str1 = "hello";
char *title  ;
title = strcat(str1, "World");
printf("%s",title);
 
You need to allocate space for it. Without any space, it is going outside what it automatically allocated
Code:
char str1[32] = "hello";  /* will allocate 32 but only use 6 */
/* Concatenate the string - works like += */
strcat (str1, "World");
printf ("%s\n", str1);
 
Code:
char *str1 = "hello";
Not to mention the fact that str1 is pointing to a constant literal string, so even if you try to change it like this:
Code:
strcpy( str1, "HELLO" );
it should still blow up, since it's trying to change a constant. This may work fine on some platforms that don't enforce constant data very strictly, but it's definitely wrong and won't work on all platforms.
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top