Overflows are caused by how you use strings. Basically it happens when you go beyond the space you've allocated and start writing in "random" memory locations. It can happen if you assume something will fit in an array and don't check if you go past the end of it. You can easily achieve this with the gets function (gcc even issues a warning when you use it), since it doesn't take any parameters that tells it how long the string is.
Code: Select all
#include <stdio.h>
int main() {
char* test = "0123456789";
// test now contains a proper null-terminated string
puts(test);
char buffer[7];
puts("Enter a 7-letter word");
gets(buffer);
puts(buffer);
char buffer2[8];
puts("Now enter a 8-letter word and see what happens :)");
gets(buffer2);
puts(buffer2);
}
As I was writing code to show an overflow this situation arose. I've reached the conclusion that the first input works for 7-letter strings because the allocated space for the 7-byte buffer is rounded up to be divisible by the size of int (which is 4 on 32-bit systems and 8 on 64-bit systems). So char buffer[7] and char buffer[8] is actually equal, with gcc on linux at least. It fails when putting a 8-letter word in buffer2 because the null-terminator will overwrite whatever comes next on the stack. If that's the return address for the function you can make it execute non-intended code.