Failed to lay out large block memory after a lot of memory malloc / free small blocks

Here is the code.

First I try to malloc and free up a lot of block memory, then I malloc a lot of small blocks of memory until the memory runs out, and I will free ALL of these small blocks.

After that, I try to malloc a large block of memory.

#include <stdio.h>
#include <stdlib.h>
int main (int argc, char **argv)
{
    static const int K = 1024;
    static const int M = 1024 * K;
    static const int G = 1024 * M;

    static const int BIG_MALLOC_SIZE = 1 * G;
    static const int SMALL_MALLOC_SIZE = 3 * K;
    static const int SMALL_MALLOC_TIMES = 1 * M;

    void **small_malloc = (void **)malloc(SMALL_MALLOC_TIMES * sizeof(void *));

    void *big_malloc = malloc(BIG_MALLOC_SIZE);
    printf("big malloc first time %s\n", (big_malloc == NULL)? "failed" : "succeeded");
    free(big_malloc);

    for (int i = 0; i != SMALL_MALLOC_TIMES; ++i)
    {
        small_malloc[i] = malloc(SMALL_MALLOC_SIZE);
        if (small_malloc[i] == NULL)
        {
            printf("small malloc failed at %d\n", i);
            break;
        }
    }
    for (int i = 0; i != SMALL_MALLOC_TIMES && small_malloc[i] != NULL; ++i)
    {
        free(small_malloc[i]);
    }

    big_malloc = malloc(BIG_MALLOC_SIZE);
    printf("big malloc second time %s\n", (big_malloc == NULL)? "failed" : "succeeded");
    free(big_malloc);

    return 0;
}

Here is the result:

big malloc first time succeeded
small malloc failed at 684912
big malloc second time failed

It looks like there are pieces of memory.

I know that memory fragmentation occurs when there are many small voids in the memory, but for a large malloc size there is not enough large space.

But I already have free ALL I malloc, the memory should be empty.

Why can't I malloc a big block a second time?

I am using Visual Studio 2010 on Windows 7, I am building a 32-bit program.

+4
3

, , .

; , 3- , .

, . Sysinternals VMMap, .

, 16- , , (.. ).

1 .

+2

, , , malloc .

, malloc "", .

There is no guarantee that if you free up all memory, the arena will be reduced to its original size. It is possible that the arena still exists, and all the blocks have been placed on a free list (possibly combined into larger blocks).

The presence of this protracted arena in your address space may make it impossible to satisfy a large request for accommodation.

0
source

Source: https://habr.com/ru/post/1542295/


All Articles