为什么这个 strncpy() 实现在第二次运行时崩溃,而第一次运行正常?
strncpy
Copy characters from string Copies the first
n
characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found beforen
characters have been copied, destination is padded with zeros until a total ofn
characters have been written to it.No null-character is implicitly appended at the end of destination if source is longer than
n
(thus, in this case, destination may not be a null terminated C string).
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);
}
最佳答案
你得到一个段错误是因为
char *st3 = "ZZZZZ";
目标是一个字符串文字。字符串字面值不能被修改,它们通常存储在写保护的内存中。所以当你打电话时
strncpy(st1, st3, n);
对于 n > 0
,您试图修改字符串文字并导致崩溃(不一定,但通常)。
在复制循环中,您忘记了取消引用 strToCopy
if (strToCopy = '\0')
并写了 =
而不是 ==
,所以 strToCopy
被设置为 NULL
,导致进一步取消引用strToCopy
调用未定义的行为。
关于c - 为什么这个 strncpy() 实现会在第二次运行时崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13588118/