4

strcpy 中,遇到内存重叠,为什么结果是这样?

 2 years ago
source link: https://www.v2ex.com/t/825731
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  程序员

strcpy 中,遇到内存重叠,为什么结果是这样?

  amiwrong123 · 1 天前 · 1132 次点击
#include <stdio.h>
#include <string.h>

int main()
{
	char s[10] = "hello"; 
	printf("%s\n", strcpy(s, s + 1));
	printf("%s\n", s);

	return 0;
}

打印结果是:

ello
ello

这个我理解,把ello\0往前复制了。

#include <stdio.h>
#include <string.h>

int main()
{
	char s[10] = "hello"; 
	printf("%s\n", strcpy(s + 1, s));
	printf("%s\n", s);

	return 0;
}

打印结果却是:

helll
hhelll

这个hhelll我就不理解了。不应该是hhello

本来想试一下 strcpy 的行为,自己写个实现。但现在它的行为我不理解了。

vs2019 试的,需要按照 https://blog.csdn.net/oguro/article/details/52685662 添加宏才能运行。

第 1 条附言  ·  1 天前

谢谢各位,理解了。我本意只是根据这些基本函数的行为,自己写一遍实现练习一下。

https://paste.ubuntu.com/p/H2Fc9gKkSK/
上面写了 考虑内存重叠时,我写的 strcpy 函数,欢迎各位指正

第 2 条附言  ·  23 小时 44 分钟前

说错了,不是指正,应该是交流。毕竟这是 未定义行为,我只是按照我自己想法写了一个

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK