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