- you shall not
free()
instances that have not been allocated throughmalloc()
, though it’s unclear how the instance has been allocated before being given to that function, though it’s unlikely it’s beenmalloc()
ed as this is C++, which leads me to 2. ; - you should not
free()
C++ objects, but instead calldelete
that will trigger the destructor on instances of objects ; - instead of using a struct and calling method over it, like in C, you shall instead use a class that builds nicely the object by associating a constructor, a destructor and a few methods that handles the encapsulated data ;
- on a more general aspects of things, to answer directly your question, you should release the memory of the objects you create at the same level of function call.
i.e. here’s how you should handle your instance’s lifetime:
struct sGroupInfo* foo;
// allocate memory to foo
Thread_Restore(foo);
// release memory for foo
so when someone else (which may be you in 6 months) read your code, the object’s lifetime is explicit. If you really need to release the memory for your object in the function, then your function’s name shall reflect it in some way, so it is clear that after your function call, you can’t rely on the object being still alive.
edit:
Not the pointer passed to this function, just the sCNArr, if I should free it?
so here’s your code:
// 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;
}
so I guess you shall not.
1
solved Do I need to do a free on a struct? [closed]