程序不会在堆溢出时崩溃 [英] Program do not crash on heap overflow
问题描述
我编写了以下程序:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main(int argc, char *argv[]){
char *input;
input = (char*)malloc(16);
printf("input is : %s\n", input);
}
当我以此方式运行时:
./test `python -c 'print "A"*5000'`
它不会崩溃.而是打印数据.
it does not crash. It rather prints data.
当我在printf
之后使用free(input)
时,它崩溃了.
When I use free(input)
after printf
, it crashes.
为什么会这样?
推荐答案
显示的代码将忽略其命令行参数:
The code shown ignores its command line arguments:
int main(int argc, char *argv[]){
char *input;
input = (char*)malloc(16);
printf("input is : %s\n", input);
}
Python脚本提供什么无关紧要.但是,您的printf()
正在打印未初始化的数据.导致不确定的行为.如果printf()
不会崩溃,并且printf()
之后有一个free(input);
调用,则free()
不会崩溃.
It shouldn't matter what the Python script provides. However, your printf()
is printing uninitialized data; that leads to undefined behaviour. If the printf()
doesn't crash and there is a free(input);
call after the printf()
, then the free()
shouldn't crash.
如果您错过了复制操作并打算显示类似这样的内容,则规则是不同的:
If you missed out a copy operation and intended to show something like this, then the rules are different:
int main(int argc, char *argv[]){
char *input;
input = (char*)malloc(16);
strcpy(input, argv[1]);
printf("input is : %s\n", input);
free(input);
return 0;
}
现在,在使用argv[1]
之前,您无需检查它是否不是空指针,否则可能会导致崩溃.如果您在argv[1]
中传递了5000个字符,则会超出分配的内存范围.可能会导致崩溃的事件;尚未定义导致崩溃的原因. strcpy()
可能会失败;如果没有复制,printf()
可能不会失败(但这不能保证); free()
可能会失败,因为您的践踏超出了范围(但即使这样也无法保证).这就是不确定行为"的奇观;任何事情都会发生,这是有效的行为.
Now you are not checking that argv[1]
is not a null pointer before you use it — that could cause a crash. And you are trampling way out of bounds of the allocated memory if you pass 5000 characters in argv[1]
. Something will probably trigger a crash; it isn't defined what will cause the crash. The strcpy()
may fail; the printf()
probably won't fail if the copy doesn't (but that isn't guaranteed); the free()
will probably fail because you trampled out of bounds (but even that isn't guaranteed). Such are the wonders of 'undefined behaviour'; anything could happen and it is valid behaviour.
这篇关于程序不会在堆溢出时崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!