Why is this snippet leaking memory even if I use unique_ptr?

Hi everyone,

consider the following snippet:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <memory>

int main(){

    std::unique_ptr<int> p_to_int{new int{10}};
    auto test_rel = p_to_int.release();


    return 0;
}


Checking memory leaks with leaks -atExit -- ./main, it turns out that 16 bytes have been leaked, and I don't see why this is possible. I mean, as I'm using smart pointers, I shouldn't see them. Any help is highly appreciated.
Last edited on
See this:

http://www.cplusplus.com/reference/memory/unique_ptr/release/

release() removes the pointer from unique_ptr. Hence the pointer is not automatically deleted.
Ah, I see. Thanks. So I really have to add the line with:

delete test_rel;

and now indeed I have no leaks. Btw, why do I see that precisely 16 bytes are leaked in my first program? The sizeof(test_rel) is 8 bytes, and the size of an int is 4 bytes. Why am I seeing 16?
Last edited on
Two reasons.
1. A heap has overhead. Most heap implementations use a boundary tag method.
[Knuth, Vol. 1, pg 440-442]
2. Heap implementations guarantee that a block of memory allocated from the heap is optimally aligned.
With 64 bit architectures, 16 byte multiples satisfy both requirements.
Last edited on
Knuth - that's a blast from the past! My Vol 1 copy is dated 1973! Good books, but IMO a pity he had to invent MIX and didn't use an established language. I understand his reasons, but having to learn another language (low level at that!) at the same time as trying to learn the rest didn't help.

Thanks for that info, I wasn't aware of this!
Topic archived. No new replies allowed.