added defer test files - currently called raii tests TODO: rename?

This commit is contained in:
Richard Thier 2025-04-24 20:05:16 +02:00
parent 61781e1743
commit 544196376c
2 changed files with 59 additions and 0 deletions

24
raii_test.c Normal file
View File

@ -0,0 +1,24 @@
#include <stdio.h>
#include <stdlib.h>
#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;
}

35
raii_test.cpp Normal file
View File

@ -0,0 +1,35 @@
#include <cstdio>
#include <cstdlib>
#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;
}