I would like to ask if I’s correct the following :
MyClass *obj = new MyClass();//allocate memory
obj.Variab="HELLO";
obj=NULL;
delete obj; //free memory
Is the memory allocated for obj deleted after the last two sentences? Appreciate.THX
I would like to mention that I am working in c++ /Ubuntu. G++ is the compiler
EDIT:
What if I have?
int i=0;
list<string>l;
while (i<100)
{
MyClass *obj = new MyClass();//allocate memory
obj->Variab="HELLO";
//add the obj.valie in a list
l.push_back(obj);
i=i+1;
delete obj; //free memory
}
it is ok?
no, you should use
deletebefore assigning to NULLthis is becasue the actual parameter to delete is the address of the allocated memory, but if you assign NULL before
deleteis used, you are actually passing NULL todelete, and nothing will happen, and you will get yourself a memory leak.your edit question:
this code will not compile, as
objis not defined outside thewhilescope, in any case, also, l is alist<string>and you are trying to insertMyClass*types,this will result in another compilation error. also, you should useobj->Variaband notobj.Variab, sinceobjis a pointer.EDIT to EDIT:
well, you still got a compilation error, since
objis not defined when you are trying todeleteit. try this: