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));
}
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);
}
}
P.S 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
.
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
.