小编Set*_*246的帖子

为什么malloc似乎允许我写内存?

为什么这不会返回分段错误11?

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    char *test;
    test = (char*) (malloc(sizeof(char)*3));

    test = "foo";
    printf("%s\n", test);

    test = "foobar";
    printf("%s\n", test);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的结果是

foo
foobar
Run Code Online (Sandbox Code Playgroud)

我是C的新手,但是当我使用Mac上的gcc和Windows 10上的Windows Debugger进行编译时,它并没有像我预期的那样崩溃.

我的理解是,通过使用(char*) (malloc(sizeof(char)*3)),我正在创建一个长度为3的字符数组.然后,当我将测试分配给字符串foobar时,我正在写入6个数组位置.

我坐在这里,盯着我看似有效,可运行的代码,摸不着头脑.

c arrays malloc

-3
推荐指数
1
解决办法
129
查看次数

标签 统计

arrays ×1

c ×1

malloc ×1