48
IP_ADAPTER_INFO *ptr=new IP_ADAPTER_INFO[100];

if I free using

delete ptr;

will it lead to memory leak, if not then why ?

This is disassembly code generated by VS2005

; delete ptr;
0041351D  mov         eax,dword ptr [ptr] 
00413520  mov         dword ptr [ebp-0ECh],eax 
00413526  mov         ecx,dword ptr [ebp-0ECh] 
0041352C  push        ecx  
0041352D  call        operator delete (4111DBh) 
00413532  add         esp,4 

; delete []ptr;
00413535  mov         eax,dword ptr [ptr] 
00413538  mov         dword ptr [ebp-0E0h],eax 
0041353E  mov         ecx,dword ptr [ebp-0E0h] 
00413544  push        ecx  
00413545  call        operator delete[] (4111E5h) 
0041354A  add         esp,4 
Jonas
  • 121,568
  • 97
  • 310
  • 388
Satbir
  • 6,358
  • 6
  • 37
  • 52
  • i have read that , destructor will be called for first element in array, but whole memory will be freed, same i can see while debugging – Satbir Oct 12 '09 at 08:40
  • No, only first element is freed, others not. – Andrejs Cainikovs Oct 12 '09 at 08:45
  • 1
    @Andrej: No, that's not sure. It might happen that way, but then it might not. For PODs, it's even likely that it might not. But you never know. – sbi Oct 12 '09 at 08:49
  • 7
    What will happen when `IP_ADAPTER_INFO` ceases to be POD type? Are you going to edit all the code? You have tagged your question with C++ tag, so you should consider using `std::vector`. – Kirill V. Lyadvinsky Oct 12 '09 at 08:52
  • I highly recommend ignoring this question and instead reading [delete vs delete[]](http://stackoverflow.com/questions/4255598/delete-vs-delete) instead, whose answers are much more to the point. – Theodore Murdock May 11 '16 at 20:31
  • Delete is doing two things: invoking a destructor and freeing the allocated memory. In Visual C++ IIRC, either form of delete will correctly free the allocated memory - I would not expect the scalar form of delete to cause a memory leak or heap corruption when used on an array new. However, the incorrect delete will induce errors because of incorrect destructor invocation (only called on the first element when it should be called on each element of the array). This could lead to memory leaks or heap corruption, depending on what the destructor does (or fails to do because it wasn't called). – Zenilogix Dec 27 '21 at 22:46

6 Answers6

155

Whether this leads to a memory leak, wipes your hard disk, gets you pregnant, makes nasty Nasal Demons chasing you around your apartment, or lets everything work fine with no apparent problems, is undefined. It might be this way with one compiler, and change with another, change with a new compiler version, with each new compilation, with the moon phases, your mood, or depending on the number of neutrinos that passed through the processor on the last sunny afternoon. Or it might not.

All that, and an infinite number of other possibilities are put into one term: Undefined behavior:

Just stay away from it.

thecoshman
  • 8,394
  • 8
  • 55
  • 77
sbi
  • 219,715
  • 46
  • 258
  • 445
  • 1
    I would say that "Undefined behavior" is "bad" and should be avoided, as you say. But this also means that in some cases it Will actually leak memory and You should Always code so that you solve worst-case scenarios. Thats my opinion anyways. – Filip Ekberg Oct 12 '09 at 08:46
  • 7
    @Filip: assuming your own program invokes undefined behaviour? is that some evolved form of defensive programming? – Michael Foukarakis Oct 12 '09 at 09:30
  • 23
    +1 for being a correct. Talking about how `delete` and `delete[]` behaves in some specific implementation just gives the wrong idea. It's undefined behavior: don't do it. – jalf Oct 12 '09 at 10:03
14

Just an illustration of some "undefined" behaviors on certain OSes and compilers. Hope it could be helpful for people to debug their code.

Test 1

#include <iostream>
using namespace std;
int main()
{
  int *p = new int[5];
  cout << "pass" << endl;
  delete p;
  return 0;
}

Test 2

#include <iostream>
using namespace std;
int main()
{
  int *p = new int;
  cout << "pass" << endl;
  delete[] p;
  return 0;
}

Test 3

#include <iostream>
using namespace std;
struct C {
  C() { cout << "construct" << endl; }
  ~C() { cout << "destroy" << endl; }
};

int main()
{
  C *p = new C[5];
  cout << "pass" << endl;
  delete p;
  return 0;
}

Test 4

#include <iostream>
using namespace std;
struct C {
  C() { cout << "construct" << endl; }
  ~C() { cout << "destroy" << endl; }
};

int main()
{
  C *p = new C;
  cout << "pass" << endl;
  delete[] p;
  return 0;
}
  • Windows 7 x86, msvc 2010. Compile with default options, i.e. exception handler is enabled.

Test 1

pass

Test 2

pass

Test 3

construct
construct
construct
construct
construct
pass
destroy
# Then, pop up crash msg

Test 4

construct
pass
destroy
destroy
destroy
destroy
destroy
destroy
destroy
... # It never stop until CTRL+C
  • Mac OS X 10.8.5, llvm-gcc 4.2 or gcc-4.8 generate the same output

Test 1

pass

Test 2

pass

Test 3

construct
construct
construct
construct
construct
pass
destroy
a.out(71111) malloc: *** error for object 0x7f99c94000e8: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
zsh: abort      ./a.out

Test 4

construct
pass
a.out(71035) malloc: *** error for object 0x7f83c14000d8: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
zsh: abort      ./a.out
  • Ubuntu 12.04, AMD64, gcc 4.7

Test 1

pass

Test 2

pass

Test 3

construct
construct
construct
construct
construct
*** glibc detected *** ./a.out: munmap_chunk(): invalid pointer: 0x0000000001f10018 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x7eb96)[0x7fe81d878b96]
./a.out[0x400a5b]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed)[0x7fe81d81b76d]
./a.out[0x4008d9]
======= Memory map: ========
....
zsh: abort (core dumped)  ./a.out

Test 4

construct
destroy
destroy
destroy
destroy
destroy
destroy
destroy
destroy
...
destroy
destroy
*** glibc detected *** ./a.out: free(): invalid pointer: 0x00000000016f6008 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x7eb96)[0x7fa9001fab96]
./a.out[0x400a18]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed)[0x7fa90019d76d]
./a.out[0x4008d9]
======= Memory map: ========
...
zsh: abort (core dumped)  ./a.out
jichi
  • 6,333
  • 1
  • 31
  • 25
7

It will usually not leak because in case of POD destructors are trivial and there's no need for invoking them so delete just deallocates memory occupied by the array. Memory deallocation requires just a pointer value so it will be returned to the heap. The array accopies a contiguous block of memory and so the deallocation can be sucessful just as if it was a deallocation of a single element.

But don't rely on this since it is undefined behaviour. Maybe it works allright, maybe something horrible happens, works on this compiler, doesn't work on another and many people thank you for planting an error.

See this answer for details.

Community
  • 1
  • 1
sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • 2
    Because `new T[]` may add an `sizeof` offset regardless of the POD-ness of T, in which case `delete[]` will compensate for this. `delete` would miss the header allocation block by a few bytes, interpreting an (possibly uninitialized) element count as a header, and cause unpredicatable heap corruption. Which of course shows up only when the boss looks. – MSalters Oct 12 '09 at 09:18
  • 2
    Sure, that's why the word *usually* is there. And heap corruption is not a leak. – sharptooth Oct 12 '09 at 09:23
  • 3
    `struct A { void operator delete[](void *p, size_t t) { } };` even though `struct A` is a `POD`, `new A[10]` will allocate and store that size, and `delete[]` will have to retrieve it and pass it to operator delete – Johannes Schaub - litb Oct 12 '09 at 10:34
6

delete : calls the appropriate destructor only for the element pointed to (if needed), then frees the memory chunk

delete[] : calls the appropriate destructors for each element in its array (if needed), then frees the memory chunk

FranckSpike
  • 81
  • 1
  • 3
  • 4
    All of this is true **only** if `delete` and `delete[]` are used correctly. This question is specifically about the case where `delete` is used where `delete[]` should have been used. – CB Bailey Aug 11 '11 at 14:34
5

Using delete operator on allocations with new T[n] is undefined and will vary from compiler to compiler. AFAIK, MSVC compiler for example will produce different code than GCC.

If A points to an array that was allocated via new T[n], then you must delete it via delete[] A. The difference between delete and delete[] is straightforward - the former destroys a scalar object and the latter destroys an array.

Andrejs Cainikovs
  • 27,428
  • 2
  • 75
  • 95
  • 1
    Nobody (not even Bjarne, let alone some Bjorn) specified that only one object would be freed. It's _undefined_. (And, as I said elsewhere, I have worked with at least one compiler which freed them all.) – sbi Oct 12 '09 at 08:57
  • I guess you mean Bjarne, not Bjorn? – gnud Oct 12 '09 at 08:57
  • sbi, the behavior for particular compiler *may* be undefined. But, as I said, this compiler is not following the C++ standard. Check http://www.research.att.com/~bs/. There is few mentions for this specific question. – Andrejs Cainikovs Oct 12 '09 at 09:06
  • 1
    _this compiler_ - I don't see a reference to a specific compiler (anymore) ? "Undefined Behavior" is an ISO Standard term, and does not refer to any specific implementation. – MSalters Oct 12 '09 at 09:14
  • I'll repeat, this particular **behavior** is defined by a standard. – Andrejs Cainikovs Oct 12 '09 at 09:23
  • 4
    The C++ standard explicitly states (at least in it draft version from 13.9.2001 I have at hand) that such behavior is undefined: In the first alternative (delete object), the value of the operand of delete shall be a pointer to a non-array object or a pointer to a sub-object (1.8) representing a base class of such an object (clause 10). If not, the behavior is undefined. In the second alternative (delete array), the value of the operand of delete shall be the pointer value which resulted from a previous array new-expression.72) If not, the behavior is undefined. – Komat Oct 12 '09 at 09:32
  • @Andrejs: Chapter and verse, please. – sbi Oct 12 '09 at 09:33
  • The C++ Programming Language 6.2.6.2, 19.4.5 – Andrejs Cainikovs Oct 12 '09 at 09:39
  • 3
    Neither of those exist in my copy (C++98). Anyway, the standard only specifies what you said before the updates: One destroys a scalar object, the other destroys an array. It does *not* say what you have in your first update, that if the scalar delete is invoked on an array, the first object is destroyed. That is **not** guaranteed by the standard. It is just undefined. – jalf Oct 12 '09 at 10:06
  • I would have upvoted but after reading "Update", i better not :( – Johannes Schaub - litb Oct 12 '09 at 10:36
  • 1
    Thanks jalf, sbi, Komat. You where right, I'd admitted my mistake and updated the post. – Andrejs Cainikovs Oct 12 '09 at 10:43
  • 1
    Please update your post so that all these conflicting updates are gone / or the correct information is on top – Antti Haapala -- Слава Україні Aug 21 '17 at 15:54
-3

For array of POD it will not leak (with the most compilers). For example, MSVC generates identical code for delete and delete[] for array of POD.

Personally, I think C/C++ could be without operator delete[]. Compiler knows object size and allocated memory size is known at runtime, thus it is very simple to know is a pointer array or not and dispose memory in a right way.

EDIT:

OK, guys. Can you test at your compiler and say whether it leak?

Try to think as a compiler developer. We have new, new[], delete, delete[]. Each new has its own delete. Seems perfect and complete. Let's see what is going on when you call delete[]?

1. call vector destructor for an object
2. actual free memory

What is destructor for POD? Nothing! So, calling delete for array of POD will not leak! Even if it breaks the standard. Even if it is not recommended.

EDIT2:

This is disassembly code generated by VS2008:

operator delete[]:
78583BC3  mov         edi,edi 
78583BC5  push        ebp  
78583BC6  mov         ebp,esp 
78583BC8  pop         ebp  
78583BC9  jmp         operator delete (78583BA3h) 
Sergey Podobry
  • 7,101
  • 1
  • 41
  • 51
  • 6
    `delete[]` is definitely not some form of optimization. It's all about correctness. – sbi Oct 12 '09 at 09:35
  • Yes, but is is superfluous. People want to know whether it will leak and I answered. Why downvote? – Sergey Podobry Oct 12 '09 at 09:58
  • 2
    @Sergius: I can't speak for the others, but I down-voted it because you said "For array of POD it will not leak" - even though you somewhat played this down later. What this does is _undefined_. Period. (There are reasonable assumptions from which one can deduce possible scenarios, but they definitely won't fit all compilers or even compiler versions, so making such statement just seems wrong to me.) – sbi Oct 13 '09 at 09:09
  • 1
    Well, I said "(with the most compilers)". But thanks anyway! I will be more careful in my statement. – Sergey Podobry Oct 15 '09 at 08:15