c_mem_safety/raii_test.c

25 lines
433 B
C

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