Last active
February 3, 2018 04:43
-
-
Save lamcw/c4663f8fdf5e49bfb34695887b64cf15 to your computer and use it in GitHub Desktop.
malloc macro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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