Cute little trick for gcc or clang users: (run valgrind on it afterwards)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef __cplusplus
extern "C" {
#endif

void raii_char_free(char **);

#define raii_char_pointer char * __attribute__ ((__cleanup__(raii_char_free)))

#ifdef __cplusplus
}
#endif

void raii_char_free(char **p) {
free(*p);
}

int main (void) {
raii_char_pointer ptr = strdup("abcdefg");
printf("%s\n", ptr);
return 0;
}

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.