我定义了一个结构,所以我可以在多个函数中创建它。我是否需要为struct变量'sCNArr'做一个'免费'?
struct sGroupInfo
{
TCHAR *sComputerName;
TCHAR *sMemory;
TCHAR *sHDDCount;
TCHAR *sLogFileName;
DWORD dwOnline;
};
unsigned __stdcall Thread_Restore(void *pComputerName)
{
struct sGroupInfo *sCNArr = NULL;
sCNArr = (struct sGroupInfo *) pComputerName;
std::vector <TCHAR>sCN(128,0);
_tcscpy_s(sCN.data(),sCN.size(),(TCHAR *) sCNArr->sComputerName);
// work done here
free(sCNArr);sCNArr=NULL;
}
答案 0 :(得分:3)
free()
没有通过malloc()
分配的实例,虽然不清楚实例在被赋予该函数之前是如何分配的,尽管它不太可能是malloc()
因为这是C ++,它引导我 2。; free()
C ++对象,而是调用会在对象实例上触发析构函数的delete
; 即这里是你应该如何处理你的实例的生命周期:
struct sGroupInfo* foo;
// allocate memory to foo
Thread_Restore(foo);
// release memory for foo
因此,当其他人(可能是您在6个月内)阅读您的代码时,该对象的生命周期是明确的。如果你真的需要在函数中释放对象的内存,那么你的函数名称应该以某种方式反映它,所以你的函数调用后很明显,你不能依赖于物体还活着。
编辑:
不是指针传递给这个函数,只是sCNArr,如果我应该释放它?
所以这是你的代码:
// you give a pointer to some address in the memory to the function
// so basically let's consider that: pComputerName == 0x42
unsigned __stdcall Thread_Restore(void *pComputerName) {
// you allocate one word of memory here that contains NULL, i.e. sCNArr == 0x00
struct sGroupInfo *sCNArr = NULL;
// then you allocate the value of pComputerName to sCNArr, so sCNArr == 0x42
sCNArr = (struct sGroupInfo *) pComputerName;
// …
// if you free something here, you're deallocating the memory at the address 0x42
// which will end up in undefined behaviour and/or crash if you did not allocate
// the memory using malloc
free(sCNArr);sCNArr=NULL;
}
所以我想你不会。