2

I'm trying to call malloc() in an infinite loop. This might sound weird, but I actually wanted to experiment with what would happen if I did this.

My main method:

void main() {
    while (true) {
        int64_t* ptr = malloc(sizeof(int64_t));
        if (ptr == NULL) {
            printf("Out of memory\n");
            break;
        }
    }
}

malloc() is supposed to return NULL if OS refuses to allocate more memory. When I run this program, my PC shows that memory usage is increasing even maximum allowed page file memory is committed. But the program doesn't show that "Out of memory" on the console and the operating system crashes with the Blue Screen showing the error CRITICAL PROCESS DIED.

I understand that this crash is caused by my program. But my question is why malloc didn't return NULL if the OS is running out of memory...

I compiled this program using MSVC, which comes with VS 2022.

  • 2
    Perhaps there wasn't enough memory to print "Out of memory". See [Does printf() allocate memory in C?](https://stackoverflow.com/questions/39861660/does-printf-allocate-memory-in-c) *"Often, `printf()` — or many of the other `` functions — will allocate a buffer associated with a `FILE *` when the buffer is first needed rather than when the file stream is created."* If you had been allocating bigger chunks of memory perhaps there would have been enough still available. But you have used the lot. – Weather Vane Nov 06 '22 at 17:40
  • 2
    To test Weather Vane's hypothesis, you could try changing `printf("Out of memory\n");` to `write(1, "Out of memory\n", 14);`. – Steve Summit Nov 06 '22 at 17:46
  • 5
    Note that some operating systems have this [crazy, utterly unreliable idea of providing memory that doesn't exist](https://en.wikipedia.org/wiki/Memory_overcommitment) and if your process has the temerity to actually try and use that memory, your process will be killed. Or maybe some other critical process will be killed to free some memory. **"Ok, you asked for some memory, here it is. HA HA!!! I LIED!!! NOW I KILL YOU!!!!"** Some people actually defend that... – Andrew Henle Nov 06 '22 at 17:48
  • 2
    Another likely explanation is that some other process needed some memory as well and did not properly handle the situation where none is available. – 500 - Internal Server Error Nov 06 '22 at 17:48
  • 1
    Running out of memory can be bad for any process on your computer, not just the one you wrote. – Dan Getz Nov 06 '22 at 17:49
  • AFAIK Windows allocates a fixed maximum for the code, heap, stack and all together. – Weather Vane Nov 06 '22 at 17:53
  • 1
    This might help you: https://www.youtube.com/watch?v=Fq9chEBQMFE – AR7CORE Nov 07 '22 at 09:37

0 Answers0