简体   繁体   English

C-strcpy指针

[英]C - strcpy pointer

I want to ask about strcpy. 我想问一下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 . string1和string2中第一个字符的地址发送到函数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>); ). 您需要在可写内存中分配空间(例如,通过char string1[<size>];进行堆栈char string1[<size>];或者通过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. 确保替换为所需的缓冲区空间,并至少为NULL终止添加一个额外的字节。 If you malloc() , be sure you free() later! 如果您使用malloc() ,请确保稍后再使用free()

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. 由于历史原因(字符串文字不是const ),编译器可能允许这样做,但是您基本上是在试图覆盖您在许多平台上根本无法修改的数据。

From linux man pages: 从linux手册页:

char *strcpy(char *dest, const char *src); 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. strcpy()函数将src指向的字符串(包括终止的空字节('\\ 0'))复制到dest指向的缓冲区。 The strings may not overlap, and the destination string dest must be large enough to receive the copy. 字符串不能重叠,并且目标字符串dest必须足够大才能接收副本。

You have a problem with your *dest pointer, since it's pointing to a string literal instead of allocated, modifiable memory. * dest指针存在问题,因为它指向的是字符串文字而不是分配的可修改内存。 Try defining string one as char string1[BUFFER_LENGTH]; 尝试将字符串1定义为char string1[BUFFER_LENGTH]; or allocate it dynamically with malloc() . 或使用malloc()动态分配它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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