简体   繁体   中英

free() working with iOS Simulator but not on real device

- (void)viewDidLoad
{
    [super viewDidLoad];
    int Byte = 128 * 1000;
    char *po[Byte];
    for (int i = 0; i < Byte; i++){
        po[i] = (char *)calloc(1024, sizeof(char));
        if (po[i] == NULL) {
            printf("can not calloc.");
        }
    }
    sleep(1);
    for (int j = 0; j < Byte; j++){
        free(po[j]);
    }
}

simulator retain memory then call to Free() and release memory as expected, But on real device, it is not release memory. it's retain 128MB. How do I do to release memory on real device?

The code you've posted looks fine but you may find that your method for detecting how much memory the process is using is faulty.

Typically, memory allocated from the operating system to the process is not returned to the operating system (until process exit), instead it's held by the process in a free pool in case you need it again, something like:

+----------------+
| process        |
|    (malloc)    |
|       ^        |
|       |        |
|       v        |
| +-----------+  |  +------------------+
| | free pool |<-+--| Operating system |
| +-----------+  |  +------------------+
+----------------+

So, if you're measuring the memory used by the process, it will rise by (about) 128M as you allocate the memory but it will not reduce when you free it.

You could test this indirectly by simply allocating the memory again to see if the process space increases or stays at the levels reached the first time.

You could also add debug statements to the code to ensure calloc and free are being called the correct number of times, and with valid pointers in the case of the latter.

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