0

I use the following code:

int main()
{
    int* foo = new int[10];
    foo = nullptr;
    sleep(60);
}

I build it inside XCode 7.2 and run instruments to see memory leak. I changed time delay differently and changed Instruments checking delay (from 10 to 2 sec). I tried to build project differently (Release, Debug) and also I tried to avoid compiler optimization:

int* foo = new int[10];
for (int i = 0; i < 10; ++i)
{
    foo[i] = i*3 + i^2;
}

for (int i = 0; i < 10; ++i)
{
    cout << foo[i] << endl;;
}
foo = nullptr;
sleep(60);

but I still can't see any leak inside Instruments/leak bars. What I do wrong?

Upd: I found a workaround, if I stop my console app at breakpoint and then, from the console, run

MacBook-Pro-andrey-2:~ owl$ leaks Ctrain
Process:         Ctrain [30305]
Path:            /Users/owl/Library/Developer/Xcode/DerivedData/Ctrain-cuhszmbcsswlznetmyijwykgudlz/Build/Products/Debug/Ctrain
Load Address:    0x100000000
Identifier:      Ctrain
Version:         ???
Code Type:       X86-64
Parent Process:  debugserver [30306]

Date/Time:       2015-12-23 21:30:28.768 +0300
Launch Time:     2015-12-23 21:30:25.837 +0300
OS Version:      Mac OS X 10.10.5 (14F27)
Report Version:  7
Analysis Tool:   /Applications/Xcode.app/Contents/Developer/usr/bin/leaks
Analysis Tool Version:  Xcode 7.2 (7C68)
----

leaks Report Version:  2.0
Process 30305: 390 nodes malloced for 34 KB
Process 30305: 1 leak for 48 total leaked bytes.
Leak: 0x1001054f0  size=48  zone: DefaultMallocZone_0x10006e000
    0x00000002 0x00000006 0x0000000a 0x0000000e     ................
    0x00000012 0x00000016 0x0000001a 0x0000001e     ................
    0x00000022 0x00000026 0x93554c2c 0x00007fff     "...&...,LU.....

but it is just workaround and not the answer why Instruments can't catch this leak (or any leak in my case).

Andrey Suvorov
  • 511
  • 3
  • 17

1 Answers1

0

Yes this is a memory leak as you will never be able to delete the memory but you will not be able to observe it unless you redo the operation. If you had

int main()
{
    int* foo;
    for (i = 0; i < 10; i++)
    {
        foo = new int[10];
        sleep(60);
    }
}

You would be able to observer the memory being consumed by the process increasing as we never release the memory we request before grabbing more memory.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • Sounds strange, because I need to detect one mem leak, but I've got no mem leak with Your example neither. Maybe I need to set some settings for c++ in Instruments or something else? – Andrey Suvorov Dec 23 '15 at 18:14
  • Why I will never be able to observe this leak? I can do it with crt marcos for MSVC.. – Andrey Suvorov Dec 23 '15 at 18:16
  • Since compiler is to smart and removes dummy code: `foo = new int[10];` :). You have to use this block of memory. See http://stackoverflow.com/a/14811858/1387438 – Marek R Sep 16 '16 at 16:21