所以我的理解是,一个 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 并且崩溃或打印一些奇怪的东西。这是怎么回事?