Thoughts on malloc()

* Always check for equal number of malloc()/free() calls.
• Use calloc() instead of malloc() + memset()
• Instead of allocation memory in a piece-meal manner, try to allocate a bigger chunk with malloc() and keep on resizing it with realloc() if needed.
• malloc() over-commits the memory i.e. it gives you an address which actually does not exist!
• malloc() grouping & reallocing with “more than you want”

One interesting question: What is the behavior of following program?

int main()
{
    int *p = (int*)malloc(10);
    p[10] = 1024;
}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s