-1

I want to ask about strcpy. I got problem here. Here is my code:

char *string1 = "Sentence 1";
char *string2 = "A";

strcpy(string1, string2);

I think there is no problem in my code there. The address of the first character in string1 and string2 are sent to the function strcpy. There should be no problem in this code, right? Anybody please help me solve this problem or explain to me..

Thank you.

lucifer
  • 13
  • 1
  • 2
  • 2
    Can't change string literals http://c-faq.com/strangeprob/strlitnomod.html – cnicutar Apr 03 '12 at 14:20
  • String literals (your `"Sentence 1"` and `"A"`) are unmodifiable (under penalty of Undefined Behaviour) char arrays. You cannot (reliably) `strcpy()` into such an array. – pmg Apr 03 '12 at 14:21
  • Is it okay if I will use char * string1; only? then I will use string copy twice? – kapilddit Mar 25 '14 at 07:11

3 Answers3

2

There is a problem -- your pointers are each pointing to memory which you cannot write to; they're pointing to constants which the compiler builds into your application.

You need to allocate space in writable memory (the stack via char string1[<size>]; for example, or the heap via char *string1 = malloc(<size>);). Be sure to replace with the amount of buffer space you need, and add an extra byte at least for NULL termination. If you malloc(), be sure you free() later!

mah
  • 39,056
  • 9
  • 76
  • 93
  • Thanks!! That explains why `char string2[50]` works. I am newbie in pointer, so a little confused how to use pointer. Thanks again. – lucifer Apr 03 '12 at 14:44
1

This gives undefined behaviour. The compiler may allow it, due to a quirk of history (string literals aren't const), but you're basically trying to overwrite data which on many platforms you simply cannot modify.

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
0

From linux man pages:

char *strcpy(char *dest, const char *src); The strcpy() function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy.

You have a problem with your *dest pointer, since it's pointing to a string literal instead of allocated, modifiable memory. Try defining string one as char string1[BUFFER_LENGTH]; or allocate it dynamically with malloc().