memory allocation with malloc

Shyamal Shukla shyamalshukla at gmail.com
Tue Aug 5 06:43:45 UTC 2008


Hi All,

     I am trying to validate my understanding of how malloc works by means
of the below C program which tries to corrupt essential information
maintained by malloc for free() operation.

The program allocates 4, 12 byte blocks (internally 16 bytes are allocated
for each 12 byte block). Hence the total allocated space was 48 bytes.

As malloc maintains the (length of allocated block + 1), 4 bytes before the
returned pointer (from malloc), I have manipulated this length for the first
block and set it to 49 with the goal that a single free shall release all
these 4 blocks and a subsequent malloc of 15 bytes shall be from the address
of first block.

However, this does not happen. Can someone please correct my understanding
and provide me with a reference to the working of malloc() and free()?

#include<stdio.h>

int main(void)
{
    char * ptr,* ptr1, *ptr2, * ptr3, * ptr4;
    int * i;
    int n,q,p;
    int loop = 0;

    ptr1 = (char *)malloc(12);
    i = (int *)(ptr1 - 4);
    printf("\n ptr1 = %p,%d \n",ptr1,*i);
    printf("\n %d:%d:%d:%d\n",ptr1[-4],ptr1[-3],ptr1[-2],ptr1[-1]);
    printf("\n %d:%d:%d:%d\n",ptr1[0],ptr1[1],ptr1[2],ptr1[3]);
    printf("\n %d:%d:%d:%d\n",ptr1[4],ptr1[5],ptr1[6],ptr1[7]);
    printf("\n %d:%d:%d:%d\n",ptr1[8],ptr1[9],ptr1[10],ptr1[11]);
    *i = 49;

    ptr2 = (char *)malloc(12);
    i = (int *)(ptr2 - 4);
    printf("\n ptr2 = %p,%d \n",ptr2,*i);
    printf("\n %d:%d:%d:%d\n",ptr2[-4],ptr2[-3],ptr2[-2],ptr2[-1]);

    ptr3 = (char *)malloc(12);
    i = (int *)(ptr3 - 4);
    printf("\n ptr3 = %p,%d \n",ptr3,*i);
    printf("\n %d:%d:%d:%d\n",ptr3[-4],ptr3[-3],ptr3[-2],ptr3[-1]);

    ptr4 = (char *)malloc(12);
    i = (int *)(ptr4 - 4);
    printf("\n ptr4 = %p,%d \n",ptr4,*i);
    printf("\n %d:%d:%d:%d\n",ptr4[-4],ptr4[-3],ptr4[-2],ptr4[-1]);

    free(ptr1);
    printf("\n ------------ANALYZE-------------\n");
    printf("\n %d:%d:%d:%d\n",ptr1[-4],ptr1[-3],ptr1[-2],ptr1[-1]);
    printf("\n %d:%d:%d:%d\n",ptr1[0],ptr1[1],ptr1[2],ptr1[3]);
    printf("\n %d:%d:%d:%d\n",ptr1[4],ptr1[5],ptr1[6],ptr1[7]);
    printf("\n %d:%d:%d:%d\n",ptr1[8],ptr1[9],ptr1[10],ptr1[11]);

    ptr = (char *)malloc(15);
    i = (int *)(ptr - 4);
    printf("\n ptr = %p,%d \n",ptr,*i);
    return;
}


Thanks and Regards,
Shyamal



-- 
Linux - because life is too short for reboots...


More information about the freebsd-questions mailing list