简体   繁体   中英

How come this string doesn't overflow the buffer?

I ran this code on a mac and also on linux:

#include <stdio.h>
#include <string.h>

int main (int argc, char *argv[]){

int value = 5;
char buffer_one[8], buffer_two[8];

strcpy(buffer_one, "one");
strcpy(buffer_two, "two");

printf("[BEFORE] buffer_two is at %p and contains \'%s\'\n", buffer_two, buffer_two);
printf("[BEFORE] buffer_one is at %p and contains \'%s\'\n", buffer_one, buffer_one);
printf("[BEFORE] value is at %p and is %i (0x%08x)\n", &value, value, value);

printf("\n[STRCPY] copying %i bytes into buffer two\n\n", strlen(argv[1]));
strcpy(buffer_two, argv[1]); 

printf("[AFTER] buffer_two is at %p and contains \'%s\'\n", buffer_two, buffer_two);
printf("[AFTER] buffer_one is at %p and contains \'%s\'\n", buffer_one, buffer_one);
printf("[AFTER] value is at %p and is %i (0x%08x)\n", &value, value, value);
}

On the mac, if i entered "1234567890" as a command line argument, the 90 overflowed into buffer one as I would expect because the buffer of 8 bytes was exceeded by 2.

However if I run it on my Linux system, it takes many more characters to overflow the buffer. How come/why can I get away with exeeding the buffer in Linux?

Also as A side note, on both systems, the entire string will still be printed in buffer two and only the overflowed items in buffer one. Why would that happen? How come the rest of the characters wouldn't just go to the next? If that question wasn't phrased well, heres an example:

If I enter 1234567890 on my mac, the 1234567890 will be printed in buffer two and the 90 would be printed in buffer one. How can the 90 still fit inside buffer two even though it has overflowed. (it is the same concept on linux but it takes more than 10 bytes to overflow)

In both cases, there is a buffer overflow. A buffer overflow simply invokes undefined behavior. It might seem to work totally fine in some cases, produce no crash or segfault.

For example, a memory allocator (stack allocation in this case) might allocate slightly more memory than you requested for alignment reasons. You might actually be able to overrun the buffer in that case without any noticeable side effects, but that would actually be a really bad thing since it's hiding the bug, not eliminating it.

In this case, since it involves the stack, you're overwriting contents in the stack beyond that which was allocated for your buffer. You might start noticing really odd side effects if you introduced more variables or started calling functions. In any case, this is a very problematic scenario, and you want to be very careful to avoid buffer overflow whenever possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM