简体   繁体   中英

C - strcpy pointer

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.

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!

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.

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM