Regarding dereferencing 'void *' pointer

对着背影说爱祢 提交于 2019-11-29 14:55:09
Sourav Ghosh

Quoting C11, chapter §6.5.3.2:

The unary * operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object. If the operand has type ‘‘pointer to type’’, the result has type ‘‘type’’. If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.

So, your code causes undefined behavior.

Also, related, from chapter §6.2.5:

The void type comprises an empty set of values; it is an incomplete object type that cannot be completed.

So, a pointer to void is an invalid operand for dereference.


One probable practical case and the possible solution

Sometimes, for making generics, we cast a certain pointer to void *, pass that as argument to a function and then, inside a function we cast it back to the original type, based on some known information. This is, as per chapter §6.3.2.3, perfectly valid:

[...] A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

If this is your case, and you're dereferencing inside the function, you can cast the pointer to either

before dereferencing.

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