When I run the following code, it slowly eats up my memory and even starts using swap:
long long length = 1024ull * 1024ull * 1024ull * 2ull; // 2 GB
db = [NSMutableData dataWithLength:length];
char *array = [db mutableBytes];
for(long long i = 0; i < length - 1; i++) {
array[i] = i % 256;
}
If I run it without the for cycle no memory is used at all:
long long length = 1024ull * 1024ull * 1024ull * 2ull;
db = [NSMutableData dataWithLength:length];
char *array = [db mutableBytes];
/* for(long long i = 0; i < length - 1; i++) {
array[i] = i % 256;
} */
I can only conclude that NSMutableData is only "reserving" memory and when it is accessed then it really "allocates" it. How is it done exactly?
Is this done via hardware (CPU)?
Is there a way for NSMutableData to catch memory writes in its "reserved" memory and only then do the "allocation"?
Does this also mean that a call to [NSMutableData dataWithLength:length]
can never fail? Can it allocate any size of memory using swap to get it if needed?
If it can fail will my db variable be null?
In apple's "NSMutableData Class Reference" I have seen only vague sentences about these topics.