Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
154 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...