Dynamic Meory Allocation

Hi. I have this code
1
2
3
4
5
6
7
//length is int variable
char *hStr = new char [length+12];
delete [] hStr;
{
char *hStr = new char [30];
delete [] hStr;
}


Can i replace the code in parenthesis with this?
1
2
3
4
{
hStr = new char [30];
delete [] hStr;
}


Since hStr was already declared, wouldn't this be more efficient and faster than declaring another hStr variable again?
I'm under the impression that using delete [] hStr deletes the memory pointed to by hStr, and hStr handle doesn't get deleted till it goes out of scope. I used the second example in parenthesis and everything worked fine. I'm trying to get the most efficiency out of my program. Please help
Last edited on
Since hStr was already declared, wouldn't this be more efficient and faster than declaring another hStr variable again?

It would be neither more efficient, nor faster but you could certainly do so.
closed account (2AoiNwbp)
Those are not parenthesis, but braces, so they make up a block of code. Thus, the second hStr (declared as it is) would be a different pointer which exists inside this block.
If you ommit char* inside this block, you would be referring to the hStr above.
I'm under the expression that using delete [] hStr deletes the memory pointed to by hStr, and hStr handle doesn't get deleted till it goes out of scope.

I'm not sure of what you express here, but memory is not deleted, it gets freed by using delete[] hStr. If you get out of scope without freeing the memory with delete, you will get memory leaks.
If, on the other hand, what you want is to reuse the first hStr and assign new memory to it, you must use delete [] first.

Edit:
You need 1 delete for 1 new. If you miss 1, you get a memory leak.

regards,
Alejandro
Last edited on
You are right Alejandro, those are braces, I used wrong word. What i wanted to do was reuse the first hStr. I'm assuming the correct code would be this:
1
2
3
4
5
6
7
//length is int variable
char *hStr = new char [length+12];
delete [] hStr;
{
hStr = new char [30];
delete [] hStr;
}

What I want to know is in the first instance of delete [] hStr; besides the memory pointed to by hStr being freed, does the hStr pointer get deleted too, or can I reuse hStr again to point to new memory like i have done in second instance?
delete does not destroy pointers. It operates on the memory pointed to, so it is perfectly safe to reuse hStr. But, as I mentioned before, this will have no effect on the efficiency or speed of your program.
Topic archived. No new replies allowed.