1
#include<stdio.h>

main()
{
    char *str1="beautiful";
    char *str2="place";
    xstrcat(str1,str2);
}

xstrcat(char *s1,char *s2)
{

    char *temp;
    temp=s1;

    while(*s1!='\0')
    {
        s1++;
    }
    while(*s2!='\0')
    {
        s1++;
        *s1=*s2;
        s2++;
    }
    s1++;
    *s1='\0';
    printf("\n%s",temp);
}

Error output: Program received signal SIGSEGV, Segmentation fault. 0x000000000040055d in xstrcat (s1=0x400696 "place", s2=0x400696 "place") at strcat.c:23 23 *s1=*s2;

I am not able to write in that memory. Can anyone please tell why i am getting this error. ?

jonhopkins
  • 3,844
  • 3
  • 27
  • 39
user1762571
  • 1,888
  • 7
  • 28
  • 47
  • 2
    because you don't own that memory. – user93353 May 31 '13 at 15:43
  • 1
    Must be many duplicates for this... – hmjd May 31 '13 at 15:43
  • http://c-faq.com/malloc/malloc2.html – Kevin May 31 '13 at 15:48
  • @apprentice - Those kind of improvements should be posted as an *answer*. Fixing up the *question* kind of defeats [the purpose of SO](http://stackoverflow.com/about) ... ;-) Plus the context is lost, so none of the responses/comments make sense any more. – Leigh May 31 '13 at 19:35

1 Answers1

0

str1 is a string literal it is undefined behavior to write to that location. It would be valid to create and write to str1 if it was defined like this:

char str1[100] = "beautiful";
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740