Search code examples
objective-cmallocautomatic-ref-countingmemset

Why memory is not increasing?Has memory allocated physically?


I have tested the code in Xcode 10.3

- (void)loopObjectMalloc {
    while (1) {
        NSObject *obj = [[NSObject alloc] init];
    }
}

I expect the OOM happened, but memory not increased. Is the alloc function not memset to the physical memory ?


Solution

  • By default Automatic Reference Counting (ARC) is turned on. So obj will be released at the end of each loop and make memory not be increased.

    obj doesn't need to wait for every loops finished.

    - (void)loopObjectMalloc {
        while (1) {
            // At the beginning of each loop, `obj` is created.
            NSObject *obj = [[NSObject alloc] init];
            // End of the loop, obj is released due to out of scope.
        }
        // End of function.
    }
    

    There is no need autorelease pool to release your object. release will be inserted to your code at compile time automatically.

    retain, release, retainCount, autorelease or dealloc cannot be sent to objects. Instead, the compiler inserts these messages at compile time automatically, including [super dealloc] when dealloc is overridden.

    https://en.wikipedia.org/wiki/Automatic_Reference_Counting#Objective-C

    Note: If you want to see OOM, turn off ARC.