Does this code contain use-after-free?

2019-09-22 13:18发布

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);
}

Is passing freed pointer to printf considered use-after free?

1条回答
疯言疯语
2楼-- · 2019-09-22 13:37

You'll get undefined behaviour (google that term) several times:

  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.

  2. 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.

查看更多
登录 后发表回答