Skip to content

Instantly share code, notes, and snippets.

@lamcw
Last active February 3, 2018 04:43
Show Gist options
  • Save lamcw/c4663f8fdf5e49bfb34695887b64cf15 to your computer and use it in GitHub Desktop.
Save lamcw/c4663f8fdf5e49bfb34695887b64cf15 to your computer and use it in GitHub Desktop.
malloc macro
/* method is documentented here https://tia.mat.br/posts/2015/05/01/initializing_a_heap_allocated_structure_in_c.html */
#define ALLOC_INIT(type, ...) \
(type *)memdup((type[]){ __VA_ARGS__ }, sizeof(type))
void *memdup(const void *src, size_t sz) {
void *mem = malloc(sz);
return mem ? memcpy(mem, src, sz) : NULL;
}
#if defined(__GCC__)
__auto_type foobar = ALLOC_INIT(struct foobar, {
.field = value,
.other_field = other_value,
.yet_another_field = yet_another_value
});
#else
struct foobar *foobar = ALLOC_INIT(struct foobar, {
.field = value,
.other_field = other_value,
.yet_another_field = yet_another_value
});
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment