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,
- Your statement is decoupled with the type of the variable.
- The chances of mistyping the required size is less.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…