2012/04/19

Size of memory allocation(malloc) for c language

From: BASIC programming forum - "C": Size of memory allocated to a pointer?


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

void *my_alloc(int size) {
    int *block;

    /* bump up request so we have a place to store the size */
    block = malloc(size+sizeof(int));
    if (block == NULL)
        return NULL;

    /* store the size */
    *block = size;
    /* and return pointer to next place (automatically scaled) */
    return block + 1;
}

void my_free(void *block0) {
    int *block = block0;

    /* go back to the actual allocation address */
    block--;
    free(block);
}

int my_msize(void *block0) {
    int *block;

    /* back up to the size of the block */
    block = (int *)block0 - 1;

    return *block;
}

int main() {
    char *p;
    int rc;

    p = my_alloc(50);
    printf("Size of p is %d\n", my_msize(p));
    my_free(p);
    return 0;
}

沒有留言: