这是一个基本的例子:
#include <all the basic stuff>
int main(void) {
char *name = (char *) malloc(2 * sizeof(char));
if(name == NULL) {
fprintf(stderr, "Error: Unable to allocate enough memory!\n");
return EXIT_FAILURE;
}
strcpy(name, "Bob Smith");
printf("Name: %s\n", name);
free(name);
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
因为我只分配2个字节的信息(2个字符),所以当我执行strcpy时应该会出现某种错误,对吧?这不会发生,而只是将字符串复制,打印出来,释放内存并成功退出.为什么会发生这种情况,如何正确使用malloc?