简体   繁体   中英

Can't detect C leaks in xcode 9 instruments

I'm trying to use instruments for the first time. So, I wrote a small C program to detect memory leaks in instruments.

Code:

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

int main()
{
    int *temp = NULL;
    temp = (int*)malloc(100*sizeof(int));
    for (int i = 0; i<100; ++i) {
        temp[i] = i;
    }
    printf("%d", *(temp+1));
    printf("Hello   ");
    temp = NULL;
    usleep(10000000);
    printf("%d", *(temp+1));
}

在此处输入图片说明


When I use free(temp) 在此处输入图片说明


In the 1st pic, there are no leaks but in the below panel we can see the allocated details.

In the 2nd pic, there are no leaks but in the below panel we can see there are no details.

Why is that? Can anybody explain the output(top and below panels)?

Thank you!


Update:

You mean like this?

int main()
{
    char **temp = NULL;
    temp = (char**)malloc(100*sizeof(char*));
    for (int i = 0; i<100; ++i) {
        temp[i] = (char *)malloc(100*sizeof(char));
        temp[i]=NULL;
        usleep(2000000);
    }
}

在此处输入图片说明

PS I tagged C++ because I think the above code can be written in C++ also. Please remove the tag if I'm wrong.

There is no problem with your code. It creates a memory leak as you expected. The problem(actually its good) is with the Xcode.

Xcode optimises your code to remove all the memory leaks. Thats why instruments not showing any memory leaks.

To see your memory leaks, disable the optimisations in the Xcode.

在此处输入图片说明

Select None [-O0] to disable all the optimisations.


You use intstruments to profile the final production code. So, don't change the Release settings. You may forget to change it back and your program will not be optimised.

Instead edit the scheme of Profile from Release to Debug . Doing this you can always get optimised code for the Release .

1). Click on executable icon 在此处输入图片说明

2). Click on Edit Scheme . 在此处输入图片说明

3). Change the Build Configuration to Debug . 在此处输入图片说明

Now, whenever you profile your code, you will get all the errors as your code is not optimised.

To profile your release code, change it back to Release in the Build Configuration .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM