Why does malloc memory fail on Windows x64?

卉航 林 20 Reputation points


In a windows x64 c++ program, a function will malloc 400M of memory each time it enters and then release it at the end. This function will be called continuously in the program. There is almost no memory leak in the whole program, and the computer has 16G memory.

Every time I start the program, it will run for a long time. The program crashed twice in the last few months. It was found that the program crashed because it failed to malloc 400M memory and return a nullptr, and then directly used this null pointer (the program did not judge nullptr). But I can guarantee that the memory is far enough at the crashed time.

My question is why malloc still fails when the computer's memory is large enough. The possible reason I found is that the largest continuous memory block may be smaller than 400M due to memory fragmentation, which leads to malloc failure. But as far as I know malloc may not require a contiguous piece of physical memory, but only contiguous virtual addresses. So is it possible that this is the reason for malloc failure? Is there any other reason?

I checked a lot of information, but still can't find a definite reason.

A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,441 questions
{count} votes