为什么这个strncpy()实现在第二次运行时崩溃,而第一次运行正常?
函数strncpy
从字符串复制
n字符将源的第一个字符复制到目标.如果在n复制字符之前找到源C字符串的末尾(由空字符表示),则使用零填充目标,直到n已向其写入总计字符.如果source长于
n(因此,在这种情况下,destination可能不是空终止的C字符串),则在目标的末尾不会隐式附加空字符.
char *strncpy(char *src, char *destStr, int n)
{
char *save = destStr; //backing up the pointer to the first destStr char
char *strToCopy = src; //keeps [src] unmodified
while (n > 0)
{
//if [n] > [strToCopy] length (reaches [strToCopy] end),
//adds n null-teminations to [destStr]
if (strToCopy = '\0')
for (; n > 0 ; ++destStr)
*destStr = '\0';
*destStr = *strToCopy;
strToCopy++;
destStr++;
n--;
//stops copying when reaches [dest] end (overflow protection)
if (*destStr == '\0')
n = 0; //exits loop
}
return save;
}
/////////////////////////////////////////////
int main()
{
char st1[] = "ABC";
char *st2;
char *st3 = "ZZZZZ";
st2 = (char *)malloc(5 * sizeof(char));
printf("Should be: ZZZZZ\n");
st3 = strncpy(st1, st3, 0);
printf("%s\n", st3);
printf("Should be: ABZZZZZ\n");
st3 = strncpy(st1, st3, 2);
printf("%s\n", st3);
printf("Should be: ABCZZZZZ\n");
st3 = strncpy(st1, st3, 3);
printf("%s\n", st3);
printf("Should be: ABC\n");
st3 = strncpy(st1, st3, 4);
printf("%s\n", st3);
printf("Should be: AB\n");
st2 = strncpy(st1, st2, 2);
printf("%s\n", st2);
printf("Should be: AB\n");
st2 = strncpy(st1, st2, 4);
printf("%s\n", st2);
}
Run Code Online (Sandbox Code Playgroud)
你得到一个分段错误,因为
char *st3 = "ZZZZZ";
Run Code Online (Sandbox Code Playgroud)
目标是字符串文字.不得修改字符串文字,并且通常将它们存储在写保护的内存中.所以当你打电话
strncpy(st1, st3, n);
Run Code Online (Sandbox Code Playgroud)
使用n > 0,您试图修改字符串文字并导致崩溃(不一定,但通常).
在复制循环中,您忘记了取消引用 strToCopy
if (strToCopy = '\0')
Run Code Online (Sandbox Code Playgroud)
并编写=而不是==,因此strToCopy设置为NULL,导致进一步解除引用strToCopy以调用未定义的行为.