Skip to content

Instantly share code, notes, and snippets.

@lpereira
Created June 14, 2018 03:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lpereira/eab5721766279de627ef4581268eb0ea to your computer and use it in GitHub Desktop.
Save lpereira/eab5721766279de627ef4581268eb0ea to your computer and use it in GitHub Desktop.
#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