From 5d296aef922547db03c2d209c7216e154dc0613c Mon Sep 17 00:00:00 2001 From: Ian Piumarta Date: Sat, 1 Feb 2025 08:58:27 +0900 Subject: [PATCH] add use-after-free test for common linked list deallocation bug --- demofiles/use-after-free-2.c | 40 ++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 demofiles/use-after-free-2.c diff --git a/demofiles/use-after-free-2.c b/demofiles/use-after-free-2.c new file mode 100644 index 0000000..71fca03 --- /dev/null +++ b/demofiles/use-after-free-2.c @@ -0,0 +1,40 @@ +// use-after-free + +#include +#include +#include + +struct Link +{ + int data; + struct Link *next; +}; + +struct Link *newLink(int data, struct Link *next) +{ + struct Link *link = (struct Link *)malloc(sizeof(struct Link)); + link->data = data; + link->next = next; + return link; +} + +int main() +{ + struct Link *list = 0; + + // create linked list of 10 elements + for (int i = 0; i < 10; ++i) + list = newLink(i*i, list); + + // print contents of list + for (struct Link *ptr = list; ptr; ptr = ptr->next) { + printf("%d\n", ptr->data); + } + + // deallocate list + for (struct Link *ptr = list; ptr; ptr = ptr->next) { + free(ptr); // ptr is now dangling in the update expression + } + + return 0; +}