在马洛克的Strlen

qua*_*tum 2 c pointers

为什么这不会返回警告?这段代码应该是什么问题?

char *str = malloc(strlen("hello" + 1));
strcpy(str, "hello");
Run Code Online (Sandbox Code Playgroud)

谢谢!

Oli*_*rth 8

你为什么要期待警告?

代码被破坏是因为你应该这样做strlen("hello") + 1,而不是strlen("hello" + 1)(相当于strlen("ello")).


xan*_*tos 6

这个

char *str = malloc(strlen("hello" + 1));
strcpy(str, "hello");
Run Code Online (Sandbox Code Playgroud)

几乎相当于:

char *temp = "hello";
char *temp2 = temp + 1;

char *str = malloc(strlen(temp2));
strcpy(str, "hello");
Run Code Online (Sandbox Code Playgroud)

temp + 1指针数学也是如此(它返回指针ello,strcpy并不检查目标是否有足够的内存(由C中的错误代码引起的"标准"内存损坏)

最终结果是strlen返回4,strcpy使用6个字节的内存,并随机删除一堆堆.