0

我在玩 memmove,我明白它是如何工作的。但每当最终结果包含的内容超过原始源大小时,它就会打印出一堆随机数。例如:

char str[] = "abcdefgh";
memmove(str + 6, str + 3, 4);
printf("%s\n", str);

abcdefdefgbdefggh当它应该给我的时候给我输出 abcdefdefg为什么其他字符被添加到str中?

4

2 回答 2

0

str外观记忆:

'a','b','c','d','e','f','g','h',0x0,?,?,?
                                 ^
                             End of buffer (terminates the string)

您将索引 3 中的 4 个字节复制到索引 6,这给出了

'a','b','c','d','e','f','d','e','f','g',?,?
                                 ^
                             End of buffer

所以你有了

a) 用 'f' 覆盖字符串终止 (0x0)

b)写在缓冲区之外(即'g'),这真的很糟糕

由于 a) 当str字符串终止消失时,您会在打印时得到奇怪的结果。

于 2016-04-07T04:53:55.330 回答
0
memmove(void *destination, void *source, size_t bytesToCopy)

添加到字符串中的其他字符是超出您声明的 char str[] 内存位置的字符。您已超出 memmove 中的缓冲区地址,并且 '\0' 的终止字符已被覆盖。因此,当您调用 printf 时,该函数将继续打印指针引用的字符,直到遇到 '\0'。

于 2016-04-07T04:45:16.950 回答