【发布时间】:2012-06-01 20:43:50
【问题描述】:
所以我的理解是,一个 C 字符串,例如“0123456789”,实际上会占用一个由 11 个字符组成的数组,其中 10 个字符用于正文,一个用于终止 null。如果这是真的,那么为什么下面的代码不会导致某种错误?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char ** argv){
char * my_string = "0123456789";
/* my string should occupy 11 bytes */
int my_len = strlen(my_string);
/* however, strlen should only return 10,
because it does not count the null byte */
char * new_string = malloc(my_len);
/* allocate memory 10 bytes wide */
memcpy(new_string, my_string, my_len);
/* copy the first 10 bytes from my_string to new_string
new_string should NOT be null terminated if my understanding
is correct? */
printf("%s\n", new_string);
/* Since new_stirng is NOT null terminated it seems like this should
cause some sort of memory exception.
WHY DOES THIS NOT CAUSE AN ERROR?
*/
return 0;
}
由于new_string 不是空终止,我希望printf 永远读取,直到它到达一些其他应用程序内存,或者随机放置在某处的0x00 并且崩溃或打印一些奇怪的东西。怎么回事?
【问题讨论】:
-
你很幸运,0x00 接近字符串。我认为,非常接近,因为在第一次使用之前内存通常是零填充的。
-
@osgx:当发生未定义的行为时,如果一切都发生了,我认为自己很幸运,让我有机会避免它......
-
如果你想搞砸一切,在 Valgrind 下运行你的程序或用 AddessSanitizer 编译它(包含在 llvm 3.1 中)。未定义意味着任何事情都可能发生,甚至什么都没有。
标签: c char segmentation-fault