指向结构的指针的malloc为什么起作用? [英] malloc of pointer to structure works why?

查看:89
本文介绍了指向结构的指针的malloc为什么起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我不小心使用的代码中

In a code I accidentally used

    list* Head = malloc(sizeof(list*));

代替正确的

    list* Head = malloc(sizeof(list));

来创建一个新的list类型节点,但是稍后工作得很好.

to create a new list type node but it worked just fine later on.

所以我的问题是为什么它能正常工作?

So my question is why did it work properly?

推荐答案

这里的想法是,malloc()没有想法(类型/大小)或与将要分配返回值的变量的关系.它使用输入参数,分配请求大小的内存,然后返回指向内存块的指针.因此,以防万一,您请求了错误大小的内存块,malloc()没有什么可以阻止您这样做.使用返回的指针后,您将成为

The idea here is, malloc() has no idea (type/size) or relation to the variable to which the return value is going to be assigned. It takes the input argument, allocates memory of the requested size and returns a pointer to the memory block, that's it. So, in case, you have requested for an erroneous size of memory block, malloc() has nothing to prevent you from doing that. Once you use the returned pointer, you'll either be

  • 浪费的内存,当分配的大小超过目标类型所需的大小时.
  • 当请求的大小小于要求的大小时,
  • 通过访问绑定内存导致未定义行为根据目标类型.
  • wasting memory, when the allocated size is more than required for target type.
  • cause undefined behavior by accessing out of bound memory, when the requested size is lesser than required as per target type.

现在,无论哪种情况,您都可以看到它工作正常.前者是有点允许的(尽管应该避免),但后者是严格的禁止使用.

Now, in either case, you may see it working properly. The former is somewhat permissible (though should be avoided) but the later is a strict no-go.

建议词:

为避免此类错误,请使用格式

To avoid these type of mistakes, use the format

  type * variable = malloc(sizeof *variable);

在这种情况下,您有两个优点,

in that case, you have two advantages,

  1. 您的语句与变量的类型分离.
  2. 迷惑所需大小的机会更少.

这篇关于指向结构的指针的malloc为什么起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆