malloc of pointer to structure works why?

不羁岁月 提交于 2019-12-13 09:11:19

问题


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.

So my question is why did it work properly?


回答1:


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.


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.


来源:https://stackoverflow.com/questions/46883222/malloc-of-pointer-to-structure-works-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!