C++: Safe way to cast an integer to a pointer - c++

I need to convert an integral type which contains an address to the actual pointer type. I could use reinterpret_cast as follows:
MyClass *mc1 = reinterpret_cast<MyClass*>(the_integer);
However, this does not perform any run-time checks to see if the address in question actually holds a MyClass object. I want to know if there is any benefit in first converting to a void* (using reinterpret_cast) and then using dynamic_cast on the result. Like this:
void *p = reinterpret_cast<void*>(the_integer);
MyClass *mc1 = dynamic_cast<MyClass*>(p);
assert(mc1 != NULL);
Is there any advantage in using the second method?

Type checking on dynamic_cast is implemented in different ways by different C++ implementations; if you want an answer for your specific implementation you should mention what implementation you are using. The only way to answer the question in general is to refer to ISO standard C++.
By my reading of the standard, calling dynamic_cast on a void pointer is illegal:
dynamic_cast<T>(v)
"If T is a pointer type, v shall be an rvalue of a pointer to complete class type"
(from 5.2.7.2 of the ISO C++ standard). void is not a complete class type, so the expression is illegal.
Interestingly, the type being cast to is allowed to be a void pointer, i.e.
void * foo = dynamic_cast<void *>(some_pointer);
In this case, the dynamic_cast always succeeds, and the resultant value is a pointer to the most-derived object pointed to by v.

No, there's no specific advantage in doing so. The moment you use reinterpret_cast, all bets are off. It's up to you to be sure the cast is valid.

Actually no serious advantage. If the void* points to something that is not a pointer to a polymorphic object you run into undefined behaviour (usually an access violation) immediately.

The safe way is to keep a record of all live MyClass objects. It's best to keep this record in a std::set<void*>, which means you can easily add, remove and test elements.
The reason for storing them as void*s is that you don't risk nastyness like creating unaligned MyClass* pointers from your integers.

First of all "reinterpreting" int to void * is a bad idea. If sizeof(int) is 4 and sizeof(void *) is 8 (64x system) it is ill-formed.
Moreover dynamic_cast is valid only for the case of the polymorphic classes.

Option 1 is your only (semi) portable/valid option.
Option 2: is not valid C++ as the dynamic_cast (as void is not allowed).
At an implementation level it requires type information from the source type to get to the destination type. There is no way (or there may be no way) to get the runtime source type information from a void* so this is not valid either.
Dynamic_Cast is used to cas up and down the type hierarchy not from unknown types.
As a side note you should probably be using void* rather than an integer to store an untyped pointer. There is potential for an int not to be large enough to store a pointer.

The safest way to handle pointers in C++ is to handle them typesafe. This means:
Never store pointers in anything else than a pointer
Avoid void pointers
Never pass pointers to other processes
consider weak_ptr if you plan to use pointers over threads
The reason for this is: what you are planning to do is unsafe and can be avoided unless you're interfacing with unsafe (legacy?) code. In this case consider MSalters' answer, but be aware that it still is a hassle.

If you know for sure that the_integer points to a known base class (that has at least one virtual member), there might in fact be an advantage: knowing that the object is of a specific derived class. But you’d have to reinterpret_cast to your base class first and then do the dynamic_cast:
BaseClass* obj = reinterpret_cast<BaseClass*>(the_integer);
MyClass* myObj = dynamic_cast<BaseClass*>(obj);
Using a void* in dynamic_cast is useless and simply wrong. You cannot use dynamic_cast to check if there’s a valid object at some arbitrary location in memory.
You should also pay attention when storing addresses in non-pointer type variables. There are architectures where sizeof(void*) != sizeof(int), e.g. LP64.

Related

Is there a safe way to cast void* to class pointer in C++

I am using a C library and I'm passing a "user pointer" to it. When I want to obtain the user pointer the library returns it as void*. I'm currently using static_cast in order to de-reference the members of the original pointer.
So my question is: is there a way to check if the static_cast succeeded?
As far as I know static_cast will not return a nullptr on failure, but rather, if I attempt to de-reference the resulting failed pointer it would be UB and probably crash the program...
Yes, static_cast is correct here.
Assuming that the void* value is only copied inside the C library, static_cast will return the original pointer value pointing to the passed object if you cast it to a pointer of the same type as it was originally.
Under some conditions you may also cast to a different type, the rules are those of reinterpret_cast (which simply casts via two static_casts with void* intermediate).
If you cast it to any type not allowed under those rules, e.g. an unrelated class type, trying to access the object through the pointer will cause undefined behavior. There is no way of detecting this mistake. You need to take care of doing it correctly yourself.
my question is: is there a way to check if the static_cast succeeded?
No. It's either correct or your program will have undefined behavior.
As far as I know static_cast will not return a nullptr on failure, but rather, if I attempt to de-reference the resulting failed pointer it would be UB
Yes, exactly that. So, when using static_cast you must be sure that the void* is actually pointing at an object of the type you cast to (or is a legal up or down cast).

Safely casting struct pointers

I had always thought that checking the pointer after casting a void* to a struct* was a valid way to avoid invalid casts. Something like
MyStructOne* pStructOne = (MyStructOne*)someVoidPointer;
if(!pStructOne)
return 0;
It appears that this is not the case as I can cast the same data to two different structs and get the same valid address. The program is then happy to populate my struct fields with whatever random data is in there.
What is a safe way of casting struct pointers?
I can't use dynamic_cast<> as it's not a class.
Thanks for the help!
If you have any control over the struct layout you can put your own type enumeration at the front of every struct to verify the type. This works in both C and C++.
If you can't use an enumeration because not all types are known ahead of time, you can use a GUID. Or a pointer to static variable or member that is unique per struct.
You can use dynamic_cast with structs or classes, as long as it has a virtual method. I would suggest you redesign your broader system to not have void*s anywhere. It's very bad practice/design.
There is no "safe way of casting" in general, because casting pointers is inherently an unsafe procedure. Casting says that you know better than the type system, so you can't expect the type system to be of any help after you started casting pointers.
In C++, you should never use C-style casts (like (T) x), and instead use the C++ casts. Now a few simple rules let you determine whether casting a pointer or reference is OK:
If you const_cast in the bad direction and modify the object, you must be sure that the object is actually mutable.
You can only static_cast pointers or references within a polymorphic hierarchy or from/to void pointer. You must be sure that the dynamic type of the object is a subtype of the cast target, or in the case of void pointers that pointer is the address of an object of the correct type.
reinterpret_cast should only be used to or from a char * type (possibly signed or unsigned), or to convert a pointer to and from an (u)intptr_t.
In every case, it is your responsibility to ensure that the pointers or references in question refer to an object of the type that you claim in the cast. There is no check that anyone else can do for you to verify this.
The (C-style) cast you are using is compile-time operation - that is to say that the compiler generates instructions to modify the pointer to one thing so that it points to another.
With inheritance relationships, this is simply addition or subtraction from the pointer.
In the case of your code, the compiler generates precisely no code whatsoever. The cast merely serves to tell the compiler that you know what you're doing.
The compiler does not generate any code that checks the validity of your operation. If someVoidPointer is null, so will be pStructOne after the cast. \
Using a dynamic_cast<>() doesn't validate that the thing being casted is actually an object at all - it merely tells you that an object with RTTI is (or can be converted to) the type you expect. If it's not an object to start with, you'll most likely get a crash.
There isn't one. And frankly, there can't be.
struct is simply an instruction for the compiler to treat the next sizeof() bytes in a particular semantic fashion - nothing less, nothing more.
You can cast any pointer into any pointer - all that changes is how the compiler would interpret the contents.
Using dynamic_cast<> is the only way, but it invokes RTTI (run type type information) to consider the potential legality of the assignment. Yeah, it's no longer an reinterpret_cast<>
It sounds like you want to make sure the object passed as a void* to your function is really the type you expect. The best approach would be to declare the function prototype with MyStructOne* instead of void* and let the compiler do the type checking.
If you really are trying to do something more dynamic (as in different types of objects can be passed to your function) you need to enable RTTI. This will allow you to interrogate the passed in object and ask it what type it is.
What is a safe way of casting struct pointers?
First, try to avoid needing to do this in the first place. Use forward declarations for structs if you don't want to include their headers. In general, you should only need to hide the data type from the signature if a function could take multiple types of data. The example for something like that is a message passing system, where you want to be able to pass arbitrary data. The sender and receiver know what types they expect, but the message system itself doesn't need to know.
Assuming you have no other alternatives, use a boost::any. This is essentially a type-safe void*; attempts to cast it to the wrong type will throw an exception. Note that this needs RTTI to work (which you generally should have available).
Note that boost::variant is a possibility if there is a fixed, limited set of possible types that can be used.
Since you have to use void*, your options are:
create a single base class including a virtual destructor (and/or other virtual methods) and use that exclusively across the libev interface. Wrap the libev interface to enforce this, and only use the wrappers from your C++ code. Then, inside your C++ code, you can dynamic_cast your base class.
accept that you don't have any runtime information about what type your void* really points to, and just structure your code so you always know statically. That is, make sure you cast to the correct type in the first place.
use the void* to store a simple tag/cookie/id structure, and use that to look up your real struct or whatever - this is really just a more manual version of #1 though, and incurs an extra indirection to boot.
And the direct answer to
What is a safe way of casting struct pointers?
is:
cast to the correct type, or a type you know to be layout compatible.
There just isn't any substitute for knowing statically what the correct type is. You presumably passed something in as a void*, so when you get that void* back you should be able to know what type it was.

What is this c++ macro doing?

I dont see what the following macro is doing? If anyone can help me see it it would be appreciated.
#define BASE_OFFSET(ClassName,BaseName)\
(DWORD(static_cast < BaseName* >( reinterpret_cast\
< ClassName* >(Ox10000000)))-Ox10000000)
If anyone is curious to know where it is coming from, it comes out of the 3rd chapter of Don Box Book Essential COM where he is building a QueryInterface function using interface tables and the above macro is somehow used to find the pointer to the interface vtable of the class, where class is the ClassName implementing the BaseName, although I dont know how it is doing that.
It tells to the compiler: "imagine there a ClassName object at 0x10000000. Where would the BaseName data begin in that object, relative to 0x10000000"?
Think of a memory layout of a class object with multiple bases:
class A: B, C{};
In the memory block that constitutes an A object, there's the chunk of data that belong to B, also a chunk of data that belongs to C, and the data that are specific to A. Since the address of at least one base's data cannot be the same as the address of the class instance as a whole, the numeric value of the this pointer that you pass to different methods needs to vary. The macro retrieves the value of the difference.
EDIT: The pointer to the vtable is, by convention, the first data member in any class with virtual functions. So by finding the address of the base data, one finds the address of its vtable pointer.
Now, about the type conversion. Normally, when you typecast pointers, the operation is internally trivial - the numeric value of the address does not depend on what type does it point to; the very notion of datatype only exists on the C level. There's one important exception though - when you cast object pointers with multiple inheritance. As we've just discussed, the this pointer that you need to pass to a base class method might be numerically different from the one of the derived object's.
So the distinction between static_cast and reinterpret_cast captures this difference neatly. When you use reinterpret_cast, you're telling the compiler: "I know better. Take this numeric value and interpret it as a pointer to what I say". This is a deliberate subversion of the type system, dangerous, but occasionally necessary. This kind of cast is by definition trivial - cause you say so.
By "trivial" I mean - the numeric value of the pointer does not change.
The static_cast is a more high level construct. In this particular case, you're casting between an object and its base. That's a reasonable, safe cast under C++ class rules - BUT it might be numerically nontrivial. That's why the macro uses two different typecasts. static_cast does NOT violate the type system.
To recap:
reinterpret_cast<ClassName* >(OxlOOOOOOO)
is an unsafe operation. It returns a bogus pointer to a bogus object, but it's OK because we never dereference it.
static_cast<BaseName*>(...)
is a safe operation (with an unsafe pointer, the irony). It's the part where the nontrivial pointer typecast happens.
(DWORD(...)-OxlOOOOOOO)
is pure arithmetic. That's where the unsafety doubles back on itself: rather than use the pointer as a pointer, we cast it back to an integer and forget that it ever was a pointer.
The last stage could be equivalently rephrased as:
((char*)(...)-(char*)OxlOOOOOOO)
if that makes more sense.
Remark about magic 0x10000000 constant.
If that constant will be 0, GCC will show warning -Winvalid-offset-of (if it is enabled, of course). Maybe other compilers do something like that.

Few doubts about casting operators in C++

The reinterpret_cast as we know can cast any pointer type to any another pointer type. The question I want to ask regarding this cast operator are:
How does reinterpret_cast work, What is the magic(the internal implementation) that allows reinterpret_cast to work?
How to ensure safety when using reinterpret_cast? As far as i know, it doesn't guarantee of safe casting, So what precaution to take while using reinterpret_cast?
What is the practical usage of this operator. I have not really encountered it in my professional programing experience, wherein I could'nt get around without using this operator.Any practical examples apart from usual int* to char* will be highly helpful and appreciated.
One other Question regarding casting operators in general:
Casting operators(static_cast, dynamic_cast, const_cast, reinterpret_cast) are all called Operators i.e is to the best of my understanding, So is it correct statement to make that casting operators cannot be overloaded unlike most other operators (I am aware not all operators can be overloaded and I am aware of which can't be(except the Q I am asking, Please refrain flaming me on that) Just I had this doubt that since they are operators, what does the standard say about these?
There is no magic. reinterpret_cast normally just means (at least try to) treat what you find at this address as if it was the type I've specified. The standard defines little enough about what it does that it could be different from that, but it rarely (if ever) really is.
In a few cases, you can get safety from something like a discriminated union. For example, if you're reading network packets, and read enough to see that what you've received is a TCP packet, then you can (fairly) safely do a reinterpret_cast from IPHdr to TCPHdr (or whatever names you happen to have used). The compiler won't (again, normally) do much though -- any safety is up to you to implement and enforce.
I've used code like I describe in 2), dealing with different types of network packets.
For your final question: you can overload casting for a class:
class XXX {
public:
operator YYY() { return whatever; }
};
This can be used for conversions in general though -- whether done by a static_cast, C-style cast, or even an implicit conversion. C++0x allows you to add an explicit qualifier so it won't be used for implicit conversions, but there's still no way to differentiate between a static_cast and a C-style cast though.
First, it's unclear what you mean by "non-standard pointer". I think your premise is flawed. Happily it doesn't seem to affect the questions.
"How does [it] work?" Well, the intent, as you can guess from the name, is to just change the interpretation of a bitpattern, perhaps extending or shorting as appropriate. This is a kind of change of type where the bitpattern is left unchanged but the interpretation and hence conceptual value is changed. And it's in contrast to a kind of change of type where the conceptual value is kept (e.g. int converted to double) while the bitpattern is changed as necessary to keep the conceptual value. But most cases of reinterpret_cast have implementation defined effect, so for those cases your compiler can do whatever it wants -- not necessarily keeping the bitpattern -- as long as it is documented.
"How to ensure safety" That is about knowing what your compiler does, and about avoiding reinterpret_cast. :-)
"What is the practical usage". Mostly it is about recovering type information that's been lost in C-oriented code where void* pointers are used to sort of emulate polymorphism.
Cheers & hth.,
reinterpret_cast generally lets you do some very bad things. In the case of casting a pointer it will permit casting from one type to another which has absolutely no reason to assume this should work. It's like saying "trust me I really want to do this". What exactly this does is unpredictable from one system to the next. On your system it might just copy the bit-patterns, where as on another one it could transform them in some (potentially useful) way.
e.g.
class Foo {
int a;
};
class Bar {
int a;
};
int main() {
Foo a;
// No inheritance relationship and not void* so must be reinterpret_cast
// if you really want to do it
Bar *b = reinterpret_cast<Bar*>(&a);
char buffer[sizeof(Bar)];
Bar *c = reinterpret_cast<Bar*>(buffer); // alignment?
}
Will quite happily let you do that, no matter what the scenario. Sometimes if you're doing low-level manipulation of things this might actually be what you want to do. (Imagine char * of a buffer casting to something user defined type)
Potential pitfalls are huge, even in the simplest case like a buffer, where alignment may well be a problem.
With dlsym() on Linux it's useful to be able to cast void* to a function pointer, which is otherwise undefined behaviour in C++. (Some systems might use separate address spaces or different size pointers!). This can only be done with reinterpret_cast in C++.
reinterpret_cast only works on pointers. The way it works is that it leaves the value of the pointer alone and changes the assumed type information about it. It says, "I know these types are not equivalent, but I want you to just pretend this is now a pointer to T2." Of course, this can cause any number of problems if you use the T2 pointer and it does not point to a T2.
There are very few guarantees about reinterpret_cast, which is why it is to be so avoided. You're really only allowed to cast from T1 to T2 and then back to T1 and know that, given some assumptions, that the final result will be the same as what you started with.
The only one I can think of is casting a char* to an unsigned char*. I know that the underlying representation is the same in my implementation so I know the cast is safe. I can't use a static cast though because it's a pointer to a buffer. In reality, you'll find very little legitimate use of reinterpret_cast in the real world.
Yes, they are operators. AFAIK you can't override them.
One "practical" use of reinterpret_cast.
I have a class where the members are not meant to be read. Example below
class ClassWithHiddenVariables
{
private:
int a;
double m;
public:
void SetVariables(int s, int d)
{
a = s;
m = d;
}
};
This class is used in a thousand places in an application without a problem.
Now, because of some reason I want see the members in one specific part. However, I don't want to touch the existing class.So break the rules as follows.
Create another class with the same bit pattern and public visibility. Here the original class contains an int and double.
class ExposeAnotherClass
{
public:
int a_exposed;
double m_exposed;
};
When you want to see members of the ClassWithHiddenVariables object, use reinterpret_cast to cast to ExposeAnotherClass. Example follows
ClassWithHiddenVariables obj;
obj.SetVariables(10, 20.02);
ExposeAnotherClass *ptrExposedClass;
ptrExposedClass = reinterpret_cast<ExposeAnotherClass*>(&obj);
cout<<ptrExposedClass->a_exposed<<"\n"<<ptrExposedClass->m_exposed;
I don't think this situation ever occurs in real world. But this is just an explanation of reinterpret_cast which considers objects as bit patterns.
reinterpret_cast tells the compiler "shut up, it's a variable of type T*" and there's no safety unless it is really a variable of type T*. On most implementations just nothing is done - the same value in the variable is passed to the destination.
Your class can have conversion operators to any type T* and those conversions will either be invokde implicitly under certain conditions or you can invoke them explicitly using static_cast.
I've used reinterpret_cast a lot in Windows programming. Message handling uses WPARAM and LPARAM parameters that need casting to the correct types.
reinterpret_cast is pretty equivalent to a C-style cast. It doesn't guarentee anything; it's there to allow you to do what you need to, in the hopes that you know what you're doing.
If you're looking to ensure safety, use dynamic_cast, as that's what it does. If the cast cannot be completed safely, dynamic_cast returns NULL or nullptr (C++0x).
Casting using the "casting operators" such as static_cast, dynamic_cast, etc.. cannot be overloaded. Straight conversions can, such as:
class Degrees
{
public:
operator double() { ... }
};
The reinterpret_cast as we know can
cast any non-standard pointer to
another non-standard pointer.
Almost, but not exactly. For example, you can't use reinterpret_cast to cast a const int* to an int*. For that, you need const_cast.
How does reinterpret_cast work, What is the magic(the internal
implementation) that allows
reinterpret_cast to work?
There's no magic at all. Ultimately, all data is just bytes. The C++ type system is merely an abstraction layer which tells the compiler how to "interpret" each byte. A reinterpret_cast is similar to a plain C-cast, in that it simply says "to hell with the type system: interpret these bytes as type X instead of type Y!"
How to ensure safety when using reinterpret_cast? As far as i know, it
doesn't guarantee of safe casting, So
what precaution to take while using
reinterpret_cast?
Well, reinterpret_cast is inherently dangerous. You shouldn't use it unless you really know what you're doing. Try to use static_cast instead. The C++ type system will protect you from doing anything too dangerous if you use static_cast.
What is the practical usage of this operator. I have not really
encountered it in my professional
programing experience, wherein I
could'nt get around without using this
operator.Any practical examples apart
from usual int* to char* will be
highly helpful and appreciated.
It has many uses, but usually these uses are somewhat "advanced". For example, if you are creating a memory pool of linked blocks, and storing pointers to free blocks on the blocks themselves, you'll need to reinterpret_cast a block from a T* to a T** to interpret the block as a pointer to the next block, rather than a block itself.

What are void pointers for in C++?

My question is simple: What are void pointers for in C++? (Those things you declare with void* myptr;)
What is their use? Can I make them point to a variable of any type?
Basically, a remnant from C.
What is their use?
In C, they were and are used widely, but in C++ I think they are very rarely, if ever, needed, since we have polymorphism, templates etc. which provide a much cleaner and safer way to solve the same problems where in C one would use void pointers.
Can I make them point to a variable of any type?
Yes. However, as others have pointed out, you can't use a void pointer directly - you have to cast it into a pointer to a concrete data type first.
Yes, this is a C construct (not C++-specific) that allows you to declare a pointer variable that points to any type. You can't really do much of anything with such a pointer except cast it back to the real object that it actually points to. In modern C++, void* has pretty much gone out of fashion, yielding in many cases to template-based generic code.
About one of the few uses that exist for void pointers in C++ is their use in overloading the new operators. All new operators return type void* by definition. Other than that, what others have said is true.
From cplusplus.com:
The void type of pointer is a special
type of pointer. In C++, void
represents the absence of type, so
void pointers are pointers that point
to a value that has no type (and thus
also an undetermined length and
undetermined dereference properties).
This allows void pointers to point to
any data type, from an integer value
or a float to a string of characters.
But in exchange they have a great
limitation: the data pointed by them
cannot be directly dereferenced (which
is logical, since we have no type to
dereference to), and for that reason
we will always have to cast the
address in the void pointer to some
other pointer type that points to a
concrete data type before
dereferencing it.
Type hiding. It does still have its valid uses in modern C++. Dig through the source code in boost and you'll find a few. Generally the use of a void* is buried very deep within the bowels of a more complex construct that ensures the type safety of the interface while doing black and evil magic within.
They did once in C perform the job of being the pointer-to-anything, a pointer you passed in to libraries and they gave back out to you as userdata. A void* is no use at all without the programmer knowing their context in some fashion, since you don't know what's on the other end, you can't do anything with the data. Except pass the pointer to some other code that does know.
What I don't understand is why people didn't just use undefined types, i.e. opaque pointers. Type safety, user data.
In modern C++, the pointer-to-void is nearly entirely superseded by polymorphism and template-generated generic code. However, you may still have to use them to interface with native C code. To use a void* safely, in any given context, only ever cast one type to a void*. That way, you know for sure what it points to. If you need more types, you could do a quick
struct safevoidptr {
base* ptr
}; or struct safevoidptr { void* ptr; int type; };
I believe that dynamic_cast might also be able to convert void* to polymorphic types, although I have never used dynamic_cast, so don't take my word for it.
A void pointer can point to anything, as long as its memory :-)
The C standard states that you can convert any pointer to a void-pointer, then cast it back without losing anything.
A pointer to void is the closest concept to an assembly language pointer. It is a generic pointer that reserves space for an address or location of something (function or datum). As others have stated, it must be cast before it can be dereferenced.
The void pointer is a popular tool for representing Object Orient concepts in the C language. One issue with the void pointer is that the content may not match the receiver's perception. If the caller sets the pointer to point to a square, but the receiving function is expecting a pointer to a cat, undefined and strange things will happen with the pointer is cast.
Since there are already so many good answers, I'd just provide one of the more common one I saw: template specialization. If I don't recall wrongly, Stroustrup book has an example of this: specializing vector as vector, then having vector to derive (privately) from vector. This way, vector will only contain straightforward easily inlined codes (i.e. call relevant functions from vector). This will reduce the number of duplication when vector is compiled in a program that uses it with many different types of pointers.
void ptr is basically an empty box. Fill it with whatever you want but make sure you label it(tupecasting)
I use them in my dynamic lists to hold more types of objects (all are pointers).
typedef void* Object;
Then when you declare a Object variable you can store any pointer in it.
It's more or less usefull depending on the needs.
I find it very usefull when you have to store any pointer somewhere and you can't just derive all your classes from just one. Other than that as the others said it's better to use templates, polimorphism etc.
Things you could do in C with void, but can't in C++ :
void*'s are automatically converted to other pointer types. (You know its a void* - you gain no type safety from forcing an explicit cast)
Struct* p = malloc( sizeof(Struct) );
// vs C++
Struct* p = (Struct*)malloc( sizeof(Struct) );
// Some will argue that that cast style is deprecated too, and c++ programmers
// need to actually do this:
Struct* p = reinterpret_cast<Struct*>malloc( sizeof(Struct) );
// See what C++ did there? By making you write Struct a 3rd time, you can now be sure
// you know what you are doing!
void*'s also did indirection counting in C, allowing greater safety when passing pointers to functions that take a pointer to a pointer.
void funcInitializingOutPtr( void** ppOut)
{
*ppOut = malloc( x );
}
int* out = NULL;
funcInitializingPtr(out); // C would signal this as an error
funcInitializingPtr(&out); // correct
// vs C++
funcInitializingPtr( (void**)&out ); // so much safer needing that exlicit cast.
funcInitializingPtr( (void**)out); // oops. thanks C++ for hiding the common error
I belive void* is memory location where you can typecast/Store anything. I some Language Pundit will disagree on this with me. but i have used it successfully in many of my project.
Only problem i see is of typesafety