malloc take some contiguous part of heap for some variable,
-------------
| p |
-------------
again malloc happens for some other pointer
------------- -----------------
| P | S |
------------- -----------------
Now realloc happens for p
------------------- -----------
| p | S |
------------------- -----------
So S space is reduced??? Does it happen?
I ran a program like this,
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *p;
char *s;
p = malloc(sizeof(*p));
printf("1:p points to %p\n", (void *)p);
//printf("1:p points to %p\n", (void *)(p+1));
s = malloc(sizeof(*s));
printf("1:s points to %p\n", (void *)s);
p = realloc(p, sizeof(*p)*2);
printf("2:p+2 points to %p\n", (void *)(p+2));
p = realloc(p, sizeof(*p)*7);
printf("3:p points to %p\n", (void *)(p));
printf("3:p+7 points to %p\n", (void *)(p+7));//should run over s's memory
printf("2:s points to %p\n", (void *)s);
free(p);
p = NULL;
free(s);
s = NULL;
return 0;
}
output:
1:p points to 0x1291010
1:s points to 0x1291030
2:p+2 points to 0x1291018
3:p points to 0x1291050 --> location of p pointed to by p is changed.
3:p+7 points to 0x129106c
2:s points to 0x1291030
So first malloc gave 0x20 = 32 bytes on its own?? 0x1291030 - 0x1291010 = 0x20 = 32 bytes.
Is it possible that if I keep increasing size of memory pointed by 'p' will lead me to s's pointed memory and then i can access s using p?
P.S
edited the question to correctly say what I wanted to say. realloc will allocate some other place in memory once the memory of s is threatened to be stomped. Its clearly visible in output.
There is no defined "least allocation unit" for malloc. It is implementation defined. It also depends on how much memory malloc tries to use for book-keeping purposes.
Regarding realloc, realloc will return the same address provided it has contiguous space to allocate for newly requested size, else, it might allocate the memory from other address and will return it and will free the memory pointed to by original pointer.
One thing which is guaranteed is that a space allocated once will not be resized without the user requesting for it i.e. in your question, the space for "S" will never automatically be reduced or resized.