April 1, 2008

Common Programming Mistakes - Buffer Overflow

Think you have a 4 bytes buffer that you want to store a string which has 4 characters. Is this right?

....
char buf[4];
....
strcpy(buf, "ABCD");
....

What people commonly forget here is the string termination byte, which is 0. That means, if you want to store 4 charactered string, you need a 5 bytes buffer. Otherwise, you'll corrupt your stack. Here is what you should do:

....
char buf[5];
....
strcpy(buf, "ABCD");
....

Hope this helps,
Burak