释放分配给空指针数组的内存 [英] Freeing memory allocated to an array of void pointers
本文介绍了释放分配给空指针数组的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我声明了一个空指针数组.每个都指向一个任意类型的值.
void **values; // Array of void pointers to each value of arbitary type
I am declaring an array of void pointers. Each of which points to a value of arbitary type.
void **values; // Array of void pointers to each value of arbitary type
初始化值如下:
values = (void**)calloc(3,sizeof(void*));
//can initialize values as: values = new void* [3];
int ival = 1;
float fval = 2.0;
char* str = "word";
values[0] = (void*)new int(ival);
values[1] = (void*)new float(fval);
values[2] = (void*)str;
//Trying to Clear the memory allocated
free(*values);
//Error: *** glibc detected *** simpleSQL: free(): invalid pointer: 0x080611b4
//Core dumped
delete[] values*;
//warning: deleting 'void*' is undefined
//Similar Error.
现在如何释放/删除分配给值的内存(无效指针数组)?
Now how do I free/delete the memory allocated for values ( the array of void pointers)?
推荐答案
您有3种动态分配的东西,需要以2种不同的方式释放它们:
You have 3 things that are dynamically allocated that need to be freed in 2 different ways:
delete reinterpret_cast<int*>( values[0]);
delete reinterpret_cast<float*>( values[1]);
free( values); // I'm not sure why this would have failed in your example,
// but it would have leaked the 2 items that you allocated
// with new
请注意,由于str
并不是动态分配的,因此它(实际上不能)不应被释放.
Note that since str
is not dynamically allocated it should not (actually cannot) be freed.
一些注意事项:
- 我假设
sizeof(void)
本来是sizeof(void*)
因为您将无法编译 - 我不会说任何关于 您看似随机的演员,除了 看起来已经准备好了的代码 普遍的灾难
- I'm assuming that the
sizeof(void)
was meant to besizeof(void*)
since what you have won't compile - I'm not going to say anything about your seemingly random casting except that it looks like code that ready for disaster in general
这篇关于释放分配给空指针数组的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文