Skip navigation

Well, everyone knows programming in C is fun.

I think the reason people hate it sometimes, and the reason for the pretty much WHY C and C++ is being pushed out/taken over by programming languages that offer automatic memory management such as Java and C#, is that anything less than absolute PERFECT memory management when programming in C will result in some pretty tough bugs.

Hard to find, deeply rooted, strange and erratically behaving BUGS.

For instance, take this line of code:

va_item * item = (va_item*)malloc(sizeof(item)); /* declare a new va_item */

Do you see anything wrong with it?

How now?

va_item * item = (va_item*)malloc(sizeof(va_item)); /* declare a new va_item */

So the top line has a very subtle mistake in it that is very easy to miss. item was only getting 4 bytes allocated to it instead of the 36 bytes its supposed to get for being a va_item.

And it produced a bug in the code that was very erratic and strange. It seemed to be more prominent in release builds than debug builds, and would result in really corrupted data (of course).

I guess keyword new in C++ might have saved the day pre-emptively here because it would have flagged that item isn’t a datatype.

But anyway.

I guess the moral of the post is: when you see weird and erratic bugs in your C programs, check ALL your mallocs that you have written recently!!!


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 )

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

%d bloggers like this: