Home > Software design >  Is my understanding of memory allocation and page size right?
Is my understanding of memory allocation and page size right?

Time:09-29

I have the following code to check process' segments boundaries:

#include <sys/types.h> 
#include <sys/stat.h>
#include <stdio.h>      
#include <stdlib.h>     
#include <unistd.h>     
#include <errno.h>      
#include <string.h>     
#include <stdbool.h>    
#include <fcntl.h>

extern char edata, etext, end;

void dump(void)
{
    printf("etext=%p, edata=%p, end=%p, sbrk(0)=%p\n", &etext, &edata, &end, sbrk(0));
}

int main(void)
{
    dump();
    char *p = (char*)malloc(1);
    printf("allocated 1 byte\n");
    dump();
    free(p);

    p = (char*)malloc(1024);
    printf("allocated 1024 bytes\n");
    dump();
    free(p);

    return 0;
}

Here is output:

>./a.out
etext=0x557f00098305, edata=0x557f0009b010, end=0x557f0009b018, sbrk(0)=0x557f00b0f000
allocated 1 byte
etext=0x557f00098305, edata=0x557f0009b010, end=0x557f0009b018, sbrk(0)=0x557f00b30000
allocated 1024 bytes
etext=0x557f00098305, edata=0x557f0009b010, end=0x557f0009b018, sbrk(0)=0x557f00b30000

I am perplexed at the output: whether allocate 1 byte or 1024 bytes, sbrk(0) returns same value at 0x557f00b30000, I can interpret this as that memory allocation is by page, not by exact request, this is fine, but why this size? The difference between 0x557f00b0f000 and 0x557f00b30000 is 135,168 which is 132K, this value looks a bit odd to me, is this the page size? How can I find it out?

CodePudding user response:

As previously stated, it depends on the implementation but to get a clue:

malloc (Notes section):

Normally, malloc() allocates memory from the heap, and adjusts the size of the heap as required, using sbrk.

mallopt - set memory allocation parameters:

M_TOP_PAD

  • This parameter defines the amount of padding to employ when calling sbrk to modify the program break. (The measurement unit for this parameter is bytes.) This parameter has an effect in the following circumstances:
    • When the program break is increased, then M_TOP_PAD bytes are added to the sbrk request.
    • the amount of padding is always rounded to a system page boundary
    • The default value for this parameter is 128*1024

CodePudding user response:

The dynamic memory allocator of the C library is managing the so-called heap but actually, this does not mean it only plays with the heap. For performance purposes especially in multithreaded environments, in the GNU C library (GLIBC), a malloc() call can hide a allocation in the heap through sbrk() but also in a mmapped memory space (also called arenas) through mmap(). There are some complex heuristics which decide where the allocated block will be.

  • Related