-3

This is a program to copy string1 to string2 from K&R book.

#include <stdio.h>
void strcpy_m(char *t1, char *t2);

int main()
{
    char *s1 = "this is 1st";
    char *s2 = "this is second";
    strcpy_m(s1, s2);
    printf("%s\t%s\n",s1, s2);
    return 0;
}

void strcpy_m(char *t1, char *t2)
{
while((*t2 = *t1) != '\0'){
    t2++;
    t1++;
   }
}

On executing this program I got segmentation fault. What is the reason?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
mrigendra
  • 1,472
  • 3
  • 19
  • 33
  • 1
    I feel like this has been asked like 10000000000 times – Idos May 03 '16 at 10:46
  • I am actually very very very weak in understanding the difference in a pointer, an array and there combined usage in strings. – mrigendra May 03 '16 at 10:50
  • K&R will not help you there, it is bad at explaining these things. In particular, the part of the book where they roll out various `strcpy` versions is pure crap, it is very harmful reading. Stop reading asap, get a better source of learning. – Lundin May 03 '16 at 11:04
  • Can you tell any good source? – mrigendra May 03 '16 at 11:15

1 Answers1

2

In your code, s1 and s2 are pointers to string literals. Hence, the contents of the memory location pointed by either of these pointers are not modifiable. Any attempt to alter the contents invokes undefined behavior.

In case, you want to have a modifiable string, make use of an array, like

#define ARRSIZ 128  //just some arbitary number

and

char s1[ARRSIZ] = "this is 1st";
char s2[ARRSIZ] = "this is second";
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261