Why are memory locations for two variables that are dynamically allocated not sequential?

I use two variables in which memory is allocated dynamically and I print the memory cells, but they are not sequential. Why?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *a = malloc(sizeof(int));
    int *b = malloc(sizeof(int));
    printf("\n a=%p \t b=%p  \n",a,b);
}

The answers I get (on Linux),

1st time:

 a=0x20a0010     b=0x20a0030

2nd time:

 a=0x657010      b=0x657030

Third time:

 a=0x139e010     b=0x139e030 

Why is there an exact difference between the memory cells of variables aand the bway it happens 1, 2, and 3 times?

Is this related to swap memory?

My processor is 64 bit.

+6
source share
4 answers

. , . Libc - sizeof int - free , , - .

, 16- . C11 7.22.3 ,

, , , ( ).

, , int, C , , 16 .

, glibc , mmap. ( 64- ) 16 4K:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *a = malloc(12345678);
    int *b = malloc(12345678);
    printf("\n a=%p \t b=%p  \n",a,b);
}

% ./a.out  

 a=0x7fb65e7b7010     b=0x7fb65dbf0010

mmap strace ./a.out -

mmap(NULL, 12349440, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fb65e7b7000
mmap(NULL, 12349440, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fb65dbf0000

, , ASLR - undefined .


P.S. 2 int , .

+8

, , . , , ASLR. ASLR , , . , . .

ISO C11 7.22.3.4 Malloc

1)

#include <stdlib.h>
void* malloc(size_t size);

2) malloc , .

3) malloc , .

+2

GNU malloc

, , , - ; , , malloc.

, malloc , , /// .

:

void* p_1 = malloc(4);
void* p_2 = malloc(4);

[oooo][xxxx][oooo][oooo]
^           ^
p_1         p_2
0

If you want continuous memory to allocate memory inside and unique_ptr with the size of two arrays and indicate your pointers at the end and the center of your pointer, which you get from the unique pointer. Remember to not remove pointers a and b.

std::unique_ptr<int> a(new int[na+nb])
int * aptr = a.get();
Int * bptr = a.get() + na;
-2
source

All Articles