user3161006
user3161006

Reputation: 41

Wrapper around malloc will it work?

I am trying to write a wrapper function around malloc. Here is the code I have written, but I am not sure will it work.

Can someone take a look at it and let me know if it works, and if not why not?

int main()
{
    int i=1;
    char *k;
    while(i<3)
    {
        i++;
        k = (char *) CountMalloc(1024);
        printf(" Total mem : %d \n Memory Address:%x \n",Totalmem,k);
    }

    printf(" Exiting\n");
    return 0;
}

Here is the function where I am allocating the memory and trying to pass the void pointer. I know this works if I declare a pointer and if I pass its address to my function and in the function call malloc and assign the address to the passed pointer. But I want to know if the following code works:

void * CountMalloc( int size )
{
    char *p;
    Totalmem += size;
    return ( malloc (size) );
}

Upvotes: 2

Views: 526

Answers (2)

dan.m was user2321368
dan.m was user2321368

Reputation: 1705

While your code will keep track of the total amount of memory request via malloc(), it isn't really keeping track of the total amount of memory used by the objects that are returned. Most allocators won't return objects of arbitrary sizes, but rather have pools of fixed sized objects (4 bytes, 8 bytes, etc.) and return the smallest object that can meet the size requested.

Even if it would allow objects of arbitrary size, it would still often round up the size of the memory block returned, depending on if the hardware allowed for byte or word addressing, or to maximize object reusabilty.

Finally, like I stated in a comment to another answer, the object will often have a hidden header that stores the size of the object, so that a subsequent free() can know how large a block is being returned.

Upvotes: 0

cdhowie
cdhowie

Reputation: 169018

A few notes:

The argument to malloc() is declared to be size_t, therefore the size parameter to CountMalloc() should also be size_t.

You don't check the result of malloc() to see if the allocation succeeded. Consider doing this instead:

void * CountMalloc(size_t size)
{
    void * allocation = malloc(size);
    if (allocation) {
        Totalmem += size;
    }
    return allocation;
}

However, note that the total amount of memory allocated is likely to be higher. Most malloc() implementations allocate more memory than you request so that they can store some information about the allocation prior to the location in memory that it returns.

Otherwise, I see no serious problems that would prevent the code from having the effect you intended.

Upvotes: 5

Related Questions