【发布时间】:2013-03-30 01:46:37
【问题描述】:
我目前正在编写一个程序,其中我陷入了 strcpy() 函数的另一种行为。这是它的简短演示......
我遇到了以下问题:Strip first and last character from C string
//This program checks whether strcpy() is needed or not after doing the modification in the string
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[] = "Nmy stringP";
char *p = mystr ;
p++;
p[strlen(p)-1] = '\0';
strcpy(mystr,p);
printf("p : %s mystr: %s\n",p,mystr);
}
输出:-
p : y strnng mystr: my strnng
如果我不使用 strcpy() 函数,那么我会得到
p : my string mystr : Nmy string
为什么会这样??
【问题讨论】:
-
我认为您不能将
strcpy与重叠的源和目标一起使用。 -
您不能重叠
strcpy()源缓冲区和目标缓冲区的内存。如果您这样做,行为是未定义的。见the documentation。 -
深入了解之前的一般提示:永远不要使用 strcpy。它是太多糟糕代码和太多系统漏洞的根源。
strncpy是首选。 -
memcpy()更可取,memmove()或重叠。要么强迫你做你最终总是用strncpy()做的事情:即硬终止目标缓冲区。srtncpy()很好(我经常使用它),但知道它是如何工作的(即它总是完全写入n字符,仅此而已)很重要。 -
@MarcB:strcpy 不是系统漏洞的来源;糟糕的系统设计是系统漏洞的根源......并且
strncpy不被排除在糟糕的系统设计之外。使用strncpy会引入一类新的漏洞:由于缺少'\0'终止而导致的信息泄露。在设计良好的算法中使用 strcpy 完全没有问题。