Why is the address not consistent when allocating single bytes?

I dynamically allocate memory like this:

char* heap_start1 = (char*) malloc(1);
char* heap_start2 = (char*) malloc(1);

      

When I do printf like this, it is surprising that addresses are not targets.

printf("%p, %p \n",heap_start1,heap_start2);

      

Result:

   0x8246008, 0x8246018

      

As you can see, there is 15 bytes of extra memory that remains defragmented. This is definitely not due to the alignment of the words. Any idea of โ€‹โ€‹this kind of alignment?

Thanks in advance!

I am using gcc on linux if that matters.

+3


source to share


4 answers


glibc malloc

, for small memory allocations less than 16 bytes, it just allocates memory as 16 bytes. This is to prevent external fragmentation when freeing this memory when the blocks of free memory are too small to be generally used for new operations malloc

.

The block allocated malloc

must also be large enough to store the data needed to track it in the data structure that stores free blocks.

This behavior, while increasing internal fragmentation, reduces the overall fragmentation of the entire system.



Source: http://repo.or.cz/w/glibc.git/blob/HEAD:/malloc/malloc.c (In particular, read line 108)

/*
...
Minimum allocated size: 4-byte ptrs:  16 bytes    (including 4 overhead)
...
*/

      

In addition, all addresses returned by a call malloc

to glibc are: 2 * sizeof(size_t)

byte aligned . It's 64 bit for 32-bit systems (like yours) and 128 bit for 64-bit systems.

+6


source


There are at least three possible reasons:



  • malloc

    it is necessary to create memory suitable for all primitive types. Data for SSE instructions must be 128-bit aligned. (There may also be other 128-bit primitive types supported by your platform that I don't currently see.)

  • A typical implementation malloc

    includes "reallocation" to store credentials for fast free

    . Not sure if GCC on Linux does this.

  • It can allocate guard bytes to enable buffer overflow detection, etc.

+4


source


If you want to allocate consecutive addresses, you must allocate them on the same malloc

char *heap_start1, *heap_start2;
heap_start1 = (char*) malloc(2 * sizeof(char));
heap_start2 = heap_start1 + 1;

      

0


source


malloc

ensures that the returned memory is correctly aligned for any underlying type. In addition, the memory block can be supplemented with some protection bytes to check for memory corruption, it depends on the settings.

0


source







All Articles