Inside my template function I have the following code:
TypeName myFunction()
{
TypeName result;
void * storage = malloc( sizeof( TypeName ) );
/*Magic code that stores a value in the space pointed to by storage*/
result = *(TypeName *)storage;
free( storage );
return result;
}
This causes an “HEAP CORRUPTION DETECTED” error.If I don’t call the free() function, the error doesn’t occur, but I am afraid that I am creating a memory leak.what would be the proper way to return the value of “storage” and then deallocate the memory?
What about:
Here, all your variables will be stored on the stack so you shouldn’t encounter heap-related problems (depending on what exactly your “magic” code does).
Is there a reason why you have your
storagearray separate fromresult? If the results will simply be copied intoresult, it would make more sense (IMHO) to only use one object (and either keep avoid*pointer to it or type-cast&resultas needed).If there is a reason to use a separate
storageandresult, you will probably get better milage usingTypeName storage = new TypeNameanddeleteinstead ofmalloc(4)andfree.