小编Don*_*ore的帖子

为什么调用malloc()没有什么区别?

这是一个基本的例子:

#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?

c malloc memory-management allocation

2
推荐指数
1
解决办法
180
查看次数

标签 统计

allocation ×1

c ×1

malloc ×1

memory-management ×1