a doubt ?
-
someobject *var=new someobject[100]; delete var; ---------------- someobject *var=new someobject[100]; var=null; --------------- what is the difference betn these two statements?
-
I'm not sure, but I think that someobject *var=new someobject[100]; delete var; frees alocated memory and someobject *var=new someobject[100]; var=null; changes the pointer to null
-
Does that mean, when the pointer is made null, the memory it pointed to also gets freed. can "var=null" be used inplace of "delete var;" ?!!
No, as C++ is not garbage collected
var=NULL
is probably an error and generates a leak in your application. Nobody will take care of the memory you leave behind undeleted. This doesn't necessarily mean a memory leak ifvar
points to some memory block that is also pointed to by some other pointer, and you properlydelete
that. Joaquín M López Muñoz Telefónica, Investigación y Desarrollo -
Does that mean, when the pointer is made null, the memory it pointed to also gets freed. can "var=null" be used inplace of "delete var;" ?!!
"var=NULL" is NOT the same as "delete var". If you imagine that
BYTE *var= new BYTE [100]
allocates a lump of memory for your use (it may be longer than 100 bytes long) and sets
var to point to it.var=NULL;
simply makes your variable point "nowhere". The memory is still allocated.
delete [] var;
frees the memory, but your variable is still pointing to the now freed patch or memory.
You could still use it, but not safely. Note the [] in the delete command as you
are freeing an array.You should be doing something like:
BYTE *var = new BYTE [100]; // Allocate some short term memory
... // Use it for some purpose
delete [] var; // "give it back"
var = NULL; // Forget about it so we don't use it my mistake.Pointers are one of those things you struggle with for a while then wake up one morning
going "Ahah!"Iain.
-
"var=NULL" is NOT the same as "delete var". If you imagine that
BYTE *var= new BYTE [100]
allocates a lump of memory for your use (it may be longer than 100 bytes long) and sets
var to point to it.var=NULL;
simply makes your variable point "nowhere". The memory is still allocated.
delete [] var;
frees the memory, but your variable is still pointing to the now freed patch or memory.
You could still use it, but not safely. Note the [] in the delete command as you
are freeing an array.You should be doing something like:
BYTE *var = new BYTE [100]; // Allocate some short term memory
... // Use it for some purpose
delete [] var; // "give it back"
var = NULL; // Forget about it so we don't use it my mistake.Pointers are one of those things you struggle with for a while then wake up one morning
going "Ahah!"Iain.