简体   繁体   English

结构指针的malloc为什么起作用?

[英]malloc of pointer to structure works why?

In a code I accidentally used 在我不小心使用的代码中

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

instead of the correct 而不是正确的

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

to create a new list type node but it worked just fine later on. 创建一个新的list类型节点,但稍后效果很好。

So my question is why did it work properly? 所以我的问题是为什么它能正常工作?

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. 这里的想法是, malloc()没有想法(类型/大小)或与将要分配返回值的变量的关系。 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. 因此,以防万一,您请求了错误大小的内存块, malloc()并没有阻止您这样做的能力。 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. 前者在某种程度上是允许的(尽管应该避免),但后者是严格的禁止使用。


Word of advice: 忠告词:

To avoid these type of mistakes, use the format 为避免这些类型的错误,请使用以下格式

  type * variable = malloc(sizeof *variable);

in that case, you have two advantages, 在这种情况下,您有两个优点,

  1. Your statement is decoupled with the type of the variable. 您的语句与变量的类型分离。
  2. The chances of mistyping the required size is less. 弄乱所需大小的机会更少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM