I want to learn more about what happens on the heap. So I look at the following C code. It basically just allocates memory on the heap for two variables:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
char *char_ptr;
int *int_ptr;
int mem_size;
if(argc < 2)
mem_size = 50;
else
mem_size = atoi(argv[1]);
printf("\t[+] allocating %d bytes of memory on the heap for char_ptr\n", mem_size);
char_ptr = (char *) malloc(mem_size);
if(char_ptr == NULL)
{
fprintf(stderr, "Error: could not allocate heap memory. \n");
exit(-1);
}
strcpy(char_ptr, "This is memory located on the heap.");
printf("char_ptr (%p) --> '%s'\n", char_ptr, char_ptr);
printf("\t[+] allocating 12 bytes of memory on the heap for int_ptr\n");
int_ptr = (int * ) malloc(12);
if(int_ptr == NULL)
{
fprintf(stderr, "Error: could not allocate heap memory.");
exit(-1);
}
*int_ptr = 31337;
printf("int_ptr (%p) --> %d\n", int_ptr, *int_ptr);
printf("\t[-] freeing char_ptr's heap memory...\n");
free(char_ptr);
printf("\t[+] allocating another 15 bytes for char_ptr\n");
char_ptr = (char *) malloc(15);
if(char_ptr == NULL)
{
fprintf(stderr,"Error: could not allocate heap memory.\n");
exit(-1);
}
strcpy(char_ptr, "new memory");
printf("char_ptr (%p) --> '%s'\n", char_ptr, char_ptr);
free(int_ptr);
free(char_ptr);
}
The output for this code looks like this:
[+] allocating 50 bytes of memory on the heap for char_ptr
char_ptr (0x8827008) --> 'This is memory located on the heap.'
[+] allocating 12 bytes of memory on the heap for int_ptr
int_ptr (0x8827040) --> 31337
[-] freeing char_ptr's heap memory...
[+] allocating another 15 bytes for char_ptr
char_ptr (0x8827050) --> 'new memory'
So I'm guessing char_ptr is pointing to the beginning of the allocated memory (0x8827008), right?
Since 50 bytes are allocated, the end of this memory should point at address 0x882702A. The next memory allocation is beginning at address 0x8827040. My question is: why is int_ptr NOT pointing to 0x882702B (the very next address after the first memory allocation)? Or in other terms: what is happening with memory in between 0x772702A and 0x8827040 ?