From 544196376ccdf86afc6aa8e8227223248b0ade51 Mon Sep 17 00:00:00 2001 From: Richard Thier Date: Thu, 24 Apr 2025 20:05:16 +0200 Subject: [PATCH] added defer test files - currently called raii tests TODO: rename? --- raii_test.c | 24 ++++++++++++++++++++++++ raii_test.cpp | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 raii_test.c create mode 100644 raii_test.cpp diff --git a/raii_test.c b/raii_test.c new file mode 100644 index 0000000..7dd646d --- /dev/null +++ b/raii_test.c @@ -0,0 +1,24 @@ +#include +#include +#include "defer.h" + +int main() { + int n; + printf("Allocate this much bytes: "); scanf("%d", &n); + void *ram = malloc(n); + defer { + free(ram); + printf("%d bytes freed\n", n); + }; + + unsigned char cs = 0; + unsigned char *bytes = ram; + for(int i = 0; i < n; ++i) { + cs += bytes[i]; + } + + printf("Checksum of found bytes: %d\n", cs); + + // exit(0); // This does not release resources! + return 0; +} diff --git a/raii_test.cpp b/raii_test.cpp new file mode 100644 index 0000000..e32ba98 --- /dev/null +++ b/raii_test.cpp @@ -0,0 +1,35 @@ +#include +#include +#include "defer.h" + +struct Test { + inline Test() { + puts("Constructor of test"); + } + inline ~Test() { + puts("Destructor of test"); + } +}; + +int main() { + int n; + printf("Allocate this much bytes: "); scanf("%d", &n); + void *ram = malloc(n); + defer { + free(ram); + printf("%d bytes freed\n", n); + }; + + unsigned char cs = 0; + unsigned char *bytes = (unsigned char*) ram; + for(int i = 0; i < n; ++i) { + cs += bytes[i]; + } + + printf("Checksum of found bytes: %d\n", cs); + + Test t; + + // exit(0); // This does not release resources! But neither calls destructors properly anyways. + return 0; +}