I have the following code
void foo()
{
char* pcBlock = new char[1000];
...
delete[] pcBl开发者_开发百科ock;
...
pcBlock = new char[100000];
...
delete[] pcBlock;
}
Would the code below result in a memory leak?
void foo()
{
char* pcBlock = new char[1000];
...
pcBlock = new char[100000];
...
delete[] pcBlock;
}
Yes, there's likely a memory leak if you don't delete[] pcBlock
in the first ...
. Reassigning a pointer does not automatically delete what it previously pointed to.
Operator "new" and "delete" should be used in pairs. Otherwise, using "new" without "deleting" causes memory leakage.
Yes, the previously allocated 1000 bytes are not freed and pcBlock is replaced with new set of memory. There is no way to release the previous 1000 bytes. So its a mem leak.
Yes, it will most likely leak memory (unless the compiler is smart enough to fix that for you, but most won't).
Maybe you should try to realloc in some way.
Yes, it will. Probably you think that the arrays will overlap and delete therefore will free the first array, but in fact they are allocated to different parts of memory.
YES IT WOULD CAUSE MEMORY LEAK
In C++ there is one simple rule:
Every call of new
should end with call of delete
at the end.
And every new[]
-> with delete[]
. Otherwise you will get memory leak.
C++ is language where programmer should control dynamic memory by himself (or using 3rd-party libs).
精彩评论