Skip to content

Instantly share code, notes, and snippets.

@exelotl
Last active December 22, 2015 11:39
Show Gist options
  • Save exelotl/6466989 to your computer and use it in GitHub Desktop.
Save exelotl/6466989 to your computer and use it in GitHub Desktop.
A macro that allocates and initialises memory simultaneously.
// allocate memory for a type, and initialise it at the same time
#define ialloc(t, ...) ialloc_impl(sizeof(t), &(t){ __VA_ARGS__ })
// helper function
inline static void* ialloc_impl(int size, void* src) {
void* dest = malloc(size);
memcpy(dest, src, size);
return dest;
}
/*
// example usage:
int* a = ialloc(int, 5);
float* b = ialloc(float[4], 1.0, 4.1, 12, 1.3);
my_type* c = ialloc(my_type, .foo="hello world", .bar=1337);
// memory can then be freed like normal
free(a);
free(b);
free(c);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment