Void is surprisingly useful.
Void is surprisingly useful.
Posted Sep 10, 2026 9:52 UTC (Thu) by alx.manpages (subscriber, #145117)In reply to: Void is surprisingly useful. by NYKevin
Parent article: Stabilizing Rust's never type
Indeed, this API lets you write malloc_T(42, void). It's not allowed in the ISO C dialect, because sizeof(void) is not valid there. But in GNU C, sizeof(void)==1, and thus this is perfectly allowed.
alx@devuan:~/tmp$ cat malloc.c
#include <stdlib.h>
#define rvalue(lv) ((void)0, (lv))
#define typeof_typename(T) typeof(*(typeof(T) *){_Generic(0, T: NULL, default: NULL)})
#define mallocarray(...) reallocarray(NULL, __VA_ARGS__)
#define malloc_T(n, T) rvalue((typeof_typename(T) *){mallocarray(n, sizeof(T))})
int
main(void)
{
void *p = malloc_T(42, void);
/*
* The memory in 'p' doesn't have an effective type yet at this
* point. This is useful for example for creating a memory pool
* from which to use memory later.
*/
int *i = p;
*i = 7;
/*
* The first byte of the pool now has an effective type of
* 'int'. The rest remains without effective type.
*/
free(p);
}
$ gcc -Wall -Wextra malloc.c
$
