这段代码是否包含使用后可以使用的代码? [英] Does this code contain use-after-free?

查看:72
本文介绍了这段代码是否包含使用后可以使用的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:

    f2中的
  1. 一旦释放,便要取消引用x,因为使用%s格式说明符对printf inging x会取消引用x,或者换句话说,它将访问x指向的内存,并且在调用free后该内存将具有不确定的内容.

  1. in f2 you are dereferencing x once it has been freed, because printfing x with the %s format specifier will dereference x, or in other words it will access the memory pointed by x, and that memory will have undetermined content after calling free.

即使删除了free(x),仍然会得到不确定的行为,因为这时您正在printf正在使用x,而x则指向有效但未初始化的内存.

even if you remove the free(x), you still get undefined behaviour, because then you are printfing x, while x is pointing to valid but non initialized memory.

这篇关于这段代码是否包含使用后可以使用的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆