
Memory Allocation and Freeing using New and Delete Operators
Quote:
> Hi,
> I am not able to free the memory which was dynamically allocated. Coulp
you
> point out where I am going wrong. Thanks in advance
> Here is the code snippet.
> #include "iostream.h"
> #include "string.h"
> void main (void)
Uhhg! Don't say void main, say int main. And yes, I know, many
teaching texts use void main. They should not.
Quote:
> {
> char* szVerify = new char[2048];
> strcpy(szVerify, "");
> strcpy(szVerify, "C:\\Temp\\Boot.ini");
> char* szTemp1 = new char[strlen(szVerify) + 1];
> szTemp1 = strstr(szVerify, "\\");
You need to read up on the care and feeding of the strstr()
function. This line stomps on the old pointer to the previously
allocated memory. That means a memory leak and a pointer
to memory that you did not allocate through a new.
Quote:
> cout << szVerify << endl << szTemp1 << endl;
> // It fails here
> if
> Temp1){
> delete [ ] szTemp1;
> }
I presume this is supposed to be the following.
if(szTemp1){
delete [ ] szTemp1;
Quote:
}
Since szTemp1 now points at the wrong spot, this will fail.
Also, testing against the pointer does not add any value.
If the pointer is NULL, deleting it is safe. If it is not NULL,
knowing that does not make calling delete any safer.
Quote:
> if (szVerify){
> delete [ ] szVerify;
> }
Same comment about the test here.
--
Dan Evens
Standard disclaimers etc. No spam please.