Quantcast
Channel: User Zan Lynx - Stack Overflow
Viewing all articles
Browse latest Browse all 40

Answer by Zan Lynx for Freeing heap on exit in C automatically

$
0
0

First I should point out that doing this is kind of useless because as others have said the operating system is going to clean all of your program out of memory on exit.

But anyway.

Have some fun with this. You'll have to modify this to register the cleanup pointers in your own functions instead of main.

#include <stdlib.h>static void **free_ptr_vec;static size_t free_ptr_vec_len;static void onexit_free_ptrs(void) {  for (size_t i = 0; i < free_ptr_vec_len; i++) {    free(free_ptr_vec[i]);  }  free(free_ptr_vec);  free_ptr_vec = NULL;  free_ptr_vec_len = 0;}void add_free_ptr(void *ptr) {  if (free_ptr_vec == NULL) {    atexit(onexit_free_ptrs);  }  free_ptr_vec_len++;  free_ptr_vec = realloc(free_ptr_vec, sizeof *free_ptr_vec * free_ptr_vec_len);  free_ptr_vec[free_ptr_vec_len - 1] = ptr;}int main() {  void *p = malloc(4000);  add_free_ptr(p);  p = malloc(16);  add_free_ptr(p);  return 0;}

Viewing all articles
Browse latest Browse all 40

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>