I have the following code:
int main(int argc, char *argv[]) {
int bufferSize = 8;
//Setting the buffer size here, which can cause a heap overflow
char *argsStr = malloc(bufferSize);
char *anotherStr = malloc(bufferSize);
//If argv[1] is greater than the buffer size, we will have an overflow
strcpy(argsStr, argv[1]);
printf("String 1: %s String 2: %s", argsStr, anotherStr);
}
I want to cause a heap overflow, so I import the param 'testtesttesttesttesttesttesttesttest'.
I would expect, since argsStr is only of size 8, it would be 'testtest' and the rest would overflow into anotherStr (for 8 bytes), but instead I see:

so argsStr is 'testtesttesttesttesttesttesttesttest' and anotherStr is 'testtesttesttesttest'
Why is this? Am I missing something with heap overflows or malloc()?
printf() doesn't know or care how much memory you allocated for the buffers. When it's printing a string with %s format, it keeps printing until it reaches the terminating zero byte. So when it's printing argsStr, it prints the entire thing, even though it overflows the 8 bytes that were allocated. This is why buffer overflows are a problem -- C pointers don't include any information about how much memory is allocated, so you can easily access memory outside the allocated space if you don't check your lengths correctly.
The memory for anotherStr was apparently allocated 16 bytes after the memory for argsStr. So when you printed that, it started from the location of argsStr[16], and printed the last 20 bytes of that string.
This is all undefined behavior, of course, so you can't depend on any specific result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With