这段代码是否包含使用后可以使用的代码? [英] Does this code contain use-after-free?
问题描述
int f2(char* x, int f) {
int i=0;
free(x);
if(f) {
printf("%s", x);
return 1;
}
return 0;
}
int main(int argc, char argv) {
char* x = malloc(10);
return f2(x, argc);
}
是否将释放的指针传递给printf视为释放后使用?
Is passing freed pointer to printf considered use-after free?
推荐答案
您将多次获得未定义的行为(谷歌搜索该术语):
You'll get undefined behaviour (google that term) several times:
-
一旦释放,便要取消引用
x
,因为使用%s
格式说明符对printf
ingingx
会取消引用x
,或者换句话说,它将访问x
指向的内存,并且在调用free
后该内存将具有不确定的内容.
f2
中的in
f2
you are dereferencingx
once it has been freed, becauseprintf
ingx
with the%s
format specifier will dereferencex
, or in other words it will access the memory pointed byx
, and that memory will have undetermined content after callingfree
.
即使删除了free(x
),仍然会得到不确定的行为,因为这时您正在printf
正在使用x
,而x
则指向有效但未初始化的内存.
even if you remove the free(x
), you still get undefined behaviour, because then you are printf
ing x
, while x
is pointing to valid but non initialized memory.
这篇关于这段代码是否包含使用后可以使用的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!