defer_free

Run Settings
LanguageC++
Language Version
Run Command
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #define CONCAT_(a,b) a##b #define CONCAT(a,b) CONCAT_(a,b) // Should they fault or ignore on 0? // Make a more safe cast function. struct DeferFreeStruct{ void **memory; ~DeferFreeStruct() { printf("Close: %s", *memory); free(*memory); } }; struct DeferFcloseStruct{ FILE **file; ~DeferFcloseStruct() { printf("Close File\n"); fclose(*file); } }; #define defer_free(memory_pointer) \ DeferFreeStruct CONCAT(defer_free_unique_name_, __COUNTER__) = {(void **)&(memory_pointer)} #define defer_fclose(file_handle) \ DeferFcloseStruct CONCAT(defer_fclose_unique_name_, __COUNTER__) = {file_handle} char *read_file(char *file_name) { FILE *file = fopen(file_name, "rb"); assert(file); defer_fclose(&file); fseek(file,0,SEEK_END); size_t file_size = ftell(file); rewind(file); char *file_data = (char *)malloc(file_size + 1); assert(file_data); fread(file_data, 1, file_size, file); file_data[file_size] = 0; return file_data; } int main() { char *vera = 0; defer_free(vera); vera = (char *)calloc(8,1); for(int i = 0; i < 8; ++i) { vera[i] = "testor\n"[i]; } char *some_file = read_file("SomeFile.txt"); defer_free(some_file); printf(vera); printf(some_file); return 0; }
Terraway
Editor Settings
Theme
Key bindings
Full width
Lines