Xcode 7.2 和 Instruments 内存泄漏不适用于 C++ 代码

Xcode 7.2 & Instruments memory leak not working for c++ code

本文关键字:不适用 适用于 C++ 代码 泄漏 内存 Instruments Xcode      更新时间:2023-10-16

我使用以下代码:

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

我在XCode 7.2中构建了它,并运行仪器来查看内存泄漏。我以不同的方式更改了时间延迟,并更改了仪器检查延迟(从10秒更改为2秒)。我试图以不同的方式构建项目(发布、调试),也试图避免编译器优化:

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);

但我仍然看不到仪器/泄漏棒内部有任何泄漏。我做错了什么?

Upd:我找到了一个变通方法,如果我在断点处停止控制台应用程序,然后从控制台运行

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.....

但这只是一种变通方法,而不是为什么Instruments无法捕捉到这种泄漏(或我的任何泄漏)的答案。

是的,这是内存泄漏,因为您永远无法删除内存,但除非您重新执行操作,否则您将无法观察到它。如果你有

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

您将能够观察到进程消耗的内存在增加,因为在获取更多内存之前,我们从未释放请求的内存。

相关文章: