Skip to content

Instantly share code, notes, and snippets.

@lpereira

lpereira/autotmp.c

Created Jun 14, 2018
Embed
What would you like to do?
#include <alloca.h>
#include <stdio.h>
#include <stdlib.h>
struct tmpvar_hook {
void *ptr;
struct tmpvar_hook *next;
};
static void tmpvar_hook_free(struct tmpvar_hook **hook) {
struct tmpvar_hook *h = *hook;
while (h) {
printf("freeing ptr %p\n", h->ptr);
free(h->ptr);
h = h->next;
}
}
#define TMPVAR_ALLOC_MALLOC_THRESHOLD 64
#define TMPVAR_ALLOC(hook_, size_) \
({ \
void *__h_ptr__ = NULL; \
if ((size_) <= TMPVAR_ALLOC_MALLOC_THRESHOLD) { \
__h_ptr__ = alloca(size_); \
printf("%zu bytes is below thresh, alloca()->%p\n", (size_), __h_ptr__); \
} else { \
__h_ptr__ = malloc(size_); \
if (__h_ptr__) { \
struct tmpvar_hook *__h_tmp__ = alloca(sizeof(struct tmpvar_hook)); \
__h_tmp__->ptr = __h_ptr__; \
__h_tmp__->next = hook_; \
hook_ = __h_tmp__; \
printf("%zu bytes is *above* thresh, malloc()->%p\n", (size_), \
__h_ptr__); \
} \
} \
__h_ptr__; \
})
int main(void) {
struct tmpvar_hook *hook __attribute__((cleanup(tmpvar_hook_free))) = NULL;
for (int i = 1; i < 1000; i += 10) {
void *ptr = TMPVAR_ALLOC(hook, i);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment