-1
#include <stdio.h>
char *strcpy_r(char* s, char* t);

int main()
{
  char *s = {"Bob"};
  char *t = {"Billy"};
  char *ptr;
  ptr = strcpy_r(s, t);
  printf("%s\n", ptr);

  return 0;
}

char* strcpy_r(char* s, char* t)
{
  if((*s = *t) != '\0')
    strcpy_r(s + 1, t + 1);
  return s;
}

I'm just doing this for practice, but when I compiled it. I got a seg fault from main. Could someone tell me what might've caused this seg fault?

alk
  • 69,737
  • 10
  • 105
  • 255
Bonnie
  • 461
  • 3
  • 11
  • 14
  • `{"Billy")` is this a typo? – Maroun Mar 20 '13 at 06:58
  • 1
    You're trying to modify a string literal. That is undefined behaviour and often crashes. – Daniel Fischer Mar 20 '13 at 06:59
  • Yeah sorry that is a typo. I'll fix that now. – Bonnie Mar 20 '13 at 07:00
  • Also your example would run into "problems" after the 4th recursive call, as then `*s` is dereferencing memory not allocated to the inital pointer `s`. Your code would only work for `t` not being shorter then `s`. – alk Mar 20 '13 at 07:04
  • Would my recursive function work outside of this context? My main focus was to write a working strcpy function recursively. – Bonnie Mar 20 '13 at 07:06
  • As long as the string `t`referrs to isn't to larger, so that recursing down into `strcpy_r()` won't eat up all the apps stack, it works. – alk Mar 20 '13 at 07:09

4 Answers4

3

Congratulations, you have invoked undefined behavior twice within one line.

First, you can't modify the contents of a string literal. So strcpy()ing onto "foo" is wrong.

Two, even if you could: you're copying a string to a buffer that is shorter than the string. This is UB again.

1

You are trying to modify a constant string. This is wrong! Chances of segfault live when you modify a constant string.

Instead do this:

  char s[10] = "Bob";
  char t[10] = "Billy";
  char *ptr;
Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
  • 1
    Voted up as that's indeed the first problem, although with that change they'll immediately hit the second problem: `s` doesn't have as much storage as `t`, so the copy will write past the end of the buffer. – rra Mar 20 '13 at 07:01
  • @H2CO3 thanks - I've modified the program – Aniket Inge Mar 20 '13 at 07:02
0

You can't overwrite the memory that's used to hold a quoted string. That'll segfault instantly.

StilesCrisis
  • 15,972
  • 4
  • 39
  • 62
0

String literals are constant, i.e. they cant change. You're also trying to copy a longer string into a shorter string, which will write beyond the bounds of the destination string.

Both of these problems leads to undefined behavior which can cause a crash.


To solve the first problem, you have to use an array for the destination string. To solve the other problem, you have to make sure the destination array is at least as large as the source string (including its terminating '\0').

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621