问题
Hey, I am wondering how void pointers is applied in the real world in terms of making a software more secure, more flexible. For example, I know that void pointers, what pointer it will cast to is hidden to outside, which will make a software more secure. Are there other reasons why you would use void pointers?
回答1:
Void pointers don't make the software any more secure.
The reason to use void* in c is a form of polymorphism - if you don't know what type the data will be you can pass a void*
In C++ there is less need to use void* and the language prevents some of the C uses
回答2:
For example, I know that void pointers, what pointer it will cast to is hidden to outside, which will make a software more secure.
Once compiled, there is nothing blatant in the assembly code that reveals the type of the pointer as a type is a higher level concept -- there are nothing but register widths in assembly code. (Theoretically by studying the assembly code you could probably deduce the size of the data type and what various fields are used for, but using a void pointer wouldn't change that. But I digress.)
That being said, the only other way something "outside" would know the pointer types would be via the API you provide (likely via a header file). But that's one of the advantages of having an API -- allowing somebody else to pass you a pointer is absolutely no guarantee that you use that type internally.
回答3:
There is no excuse even in C to use void*
in the way you mention it. This would much better be done with a pointer to an incomplete type.
typedef struct myInternal myInternal;
myInternal* getIt(void);
int doIt(myInternal*);
By that you have the same effect of hiding the internal structure / implementation to the user. But programming with that is much easier, and in particular a user can't mix up different opaque interfaces like that.
回答4:
The typical reason to use a void * is to provide a context to a user of an API/library. The context being provided is often a pointer and the void * makes it opaque. The problem the library developer has is validating the void * when it is passed back in. That can be quite challenging. In fact, the library would have been better off providing an identifier to the user which can be more easily validated without having exposed internal data.
In other words, if you are thinking of using a void *, don't.
来源:https://stackoverflow.com/questions/5124793/usage-of-void-pointer-in-c-c