Xcode的仪器中显示的Malloc内存泄漏是什么,如何解决?

问题描述 投票:0回答:1

我最近开始优化Swift应用程序中的内存使用情况。当我开始使用泄漏仪器时,我收到了超过100个“ Malloc”泄漏,没有任何描述。我环顾四周,但找不到解释。

我正在运行iOS 12.0和Xcode 10.2

我竭尽全力注释掉ViewDidLoad中正在调用的所有功能,但仍然有大约50个Malloc泄漏。我研究了导致内存泄漏的原因,并且我的代码中没有任何暗示泄漏的信息,但是我对内存管理还是相当陌生的。

对我的应用程序来说,不要泄漏很重要,因此,任何帮助将不胜感激!

ios xcode instruments
1个回答
0
投票

假设您有一个非常简单的代码

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int mem(long int mem) {
    char *buffer = malloc(sizeof(char) * mem);
    if(buffer == NULL) {
        return 1;
    } else {
        return 0;
    }
}

int main(int argc, const char * argv[]) {
    long int mem_to_alloc = 2;
    for(int i=0; i<30; i++, mem_to_alloc *= 2) {
        printf("Allocation: %d Allocating: %ld\n", i, mem_to_alloc);
        if( mem(mem_to_alloc) == 1 )
          break;
        sleep(1);
    }
    return 0;
}

首先,请确保在Build Scheme中设置正确的配置

enter image description here

Instruments中选择Leaks

enter image description here

运行代码后,您应该会在右侧的调用堆栈(Stack Trace)上看到可疑的分配。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.