use*_*221 3 c c++ memory-management
我正在声明一个void指针数组.每个都指向任意类型的值.
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.
Run Code Online (Sandbox Code Playgroud)
现在我如何释放/删除为值分配的内存(void指针数组)?
我怀疑问题是你分配的方式values:.那应该是而不仅仅是.values = (void*)calloc(3,sizeof(void))sizeof(void *)sizeof(void)
sizeof(void)可能是零或其他没有意义的东西,所以你并没有真正分配任何内存开始...它只是运气不好,分配工作,然后当你试图解除分配时弹出错误记忆.
编辑:你也在C++风格new/ deleteC风格malloc/ 交替之间提出麻烦free.它是好的,只要你不使用这两个delete东西你malloc"编辑或free东西,你new"版,但你会,如果你再这样下去他们在你的脑袋混合起来.
您有3个动态分配的东西,需要以两种不同的方式释放:
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
Run Code Online (Sandbox Code Playgroud)
请注意,由于str未动态分配,因此不应(实际上不能)释放它.
几个笔记:
sizeof(void)
是sizeof(void*)
因为你所拥有的不会编译| 归档时间: |
|
| 查看次数: |
6836 次 |
| 最近记录: |