在我的模板函数中,我有以下代码:
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;
}
这会导致“检测到堆损坏”错误。如果我不调用 free() 函数,则不会发生错误,但我担心我正在创建内存泄漏。返回的正确方法是什么“存储”的值,然后释放内存?