Adapt > Engage > Dominate

Malloc “gotcha”

Anyone who uses malloc frequently undoubtedly knows this already, but I figured I’d note it here anyway.  While writing a (very) small memory tool, I encountered a bug which caused heap corruption.  After narrowing down the problem area over the course of about four to five hours, I finally discovered the error.  I had put


instead of


and, of course, when I tried to free that memory (not to mention putting information in that block of memory), I overran the limit of that block and corrupted the heap.  For those not familiar with C, malloc attempts to get a chunk of memory of the size specified by you, the programmer.  If it is successful, it returns a pointer to that memory; otherwise, it returns NULL.  The error to watch out for, therefore, is to make sure you give malloc the size of the object you want to allocate space for, *not* the size of the pointer.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: