Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

c - Program didn't crash when buffer overflow

I want to read a string from keyboard and store in buf . I set a char buf[6] array , this array at most can store 5 characters and .

Then I type 123 456 789 it contain 11 characters and a , the program still can run , but if I type a longer string 123 456 789 123 456 789 it will crash at run time . these two inputs also out of the range of buf , but one can run , the other crash?

Here is my code:

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

void read_str();

int main(){
    read_str();
    system("pause");
    return 0;
}
void read_str(){

    char buf[6] = {};
    scanf("%[^
]",buf);
    printf("%d
",strlen(buf));
    printf("%s
",buf);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The real reason is most likely that you're just overwriting the contents of your stack since you're in a function call, and you don't actually get to memory you don't own until you to try to write characters past the bottom of it. Even though it doesn't crash, this is almost always bad because you're overwriting values that your program put there for a reason. After all, if you always crashed every time you overwrote a buffer, then buffer overflow bugs could never occur, and we know they do.

For instance, your stack is likely growing downwards. When you make a function call, you might get register values, a return address, argument values, and other things placed onto the stack. Then, and only then, will your 6 bytes for buf be allocated. If all that other stuff took up, say, 12 bytes, then you could write 18 characters to buf and still be only touching memory that you shouldn't be changing, but that your process owns. Since your process owns it, you won't get an illegal memory access, and you won't crash. Once you go past the 18 bytes, then you may very well get into memory that your process doesn't own, and you'll get a segfault and the game will be up.

The C reason is that you just have undefined behavior and weird stuff happens that you shouldn't even try to understand.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...