简体   繁体   中英

Memory leak not detected by Instruments in C

My first question is:

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

int main(int argc, const char * argv[])
{

    int *x = (int*)malloc(20*sizeof(int));
    x[0] = 10;
    x[1] = 10;

    sleep(60);
    return 0;
}

Is there a memory leak above?

Someone may consider this as a repost of this one(though the linked question is from C++ but should be same though): Why doesn't Xcode + Instrument Leaks detect this leak in simple C++ program , just maybe I didn't understand the answer there, the answer there claims there is no leak in above code, which I find contradictory. Since clearly there is a leak, we don't free memory we allocated.

Another subject is why (also in my case) Leaks instrument doesn't report it.. But there is some suggestion in the answer ...

Gone are the days when an operating system would persist heap memory after the requesting process has terminated. Nowadays, OS kernels are helpful enough to clean up.

Now, what you've shown isn't really a memory leak. It might be picked up as a leak if you did this:

int *x = (int*)malloc(20*sizeof(int));
x = NULL;

In this case, you've removed your only reference to the new memory.

It also might be picked up as a leak if you put the code into some function other than main .

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