Skip to content

Instantly share code, notes, and snippets.

@mortymacs
Created April 11, 2024 16:45
Show Gist options
  • Save mortymacs/a440b7f795c19d86394107f287e0b020 to your computer and use it in GitHub Desktop.
Save mortymacs/a440b7f795c19d86394107f287e0b020 to your computer and use it in GitHub Desktop.
Release heap memory when it goes out of scope in C
// gcc a.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void clean_name(char **name) {
printf("clean clean!");
free(*name);
}
void show(char *name) {
printf("hello %s\n", name);
}
void action() {
char *name __attribute__((cleanup (clean_name))) = malloc(sizeof(char) * 20);
strcpy(name, "test test");
show(name);
}
int main() {
action();
}
valgrind --tool=memcheck ./a.out
==575637== Memcheck, a memory error detector
==575637== Copyright (C) 2002-2022, and GNU GPL'd, by Julian Seward et al.
==575637== Using Valgrind-3.22.0 and LibVEX; rerun with -h for copyright info
==575637== Command: ./a.out
==575637==
hello mort
clean clean!==575637==
==575637== HEAP SUMMARY:
==575637== in use at exit: 0 bytes in 0 blocks
==575637== total heap usage: 2 allocs, 2 frees, 1,044 bytes allocated
==575637==
==575637== All heap blocks were freed -- no leaks are possible
==575637==
==575637== For lists of detected and suppressed errors, rerun with: -s
==575637== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
valgrind --tool=memcheck ./a.out
==574035== Memcheck, a memory error detector
==574035== Copyright (C) 2002-2022, and GNU GPL'd, by Julian Seward et al.
==574035== Using Valgrind-3.22.0 and LibVEX; rerun with -h for copyright info
==574035== Command: ./a.out
==574035==
hello mort
clean clean!==574035==
==574035== HEAP SUMMARY:
==574035== in use at exit: 20 bytes in 1 blocks
==574035== total heap usage: 2 allocs, 1 frees, 1,044 bytes allocated
==574035==
==574035== LEAK SUMMARY:
==574035== definitely lost: 20 bytes in 1 blocks
==574035== indirectly lost: 0 bytes in 0 blocks
==574035== possibly lost: 0 bytes in 0 blocks
==574035== still reachable: 0 bytes in 0 blocks
==574035== suppressed: 0 bytes in 0 blocks
==574035== Rerun with --leak-check=full to see details of leaked memory
==574035==
==574035== For lists of detected and suppressed errors, rerun with: -s
==574035== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment