Considering that the type A is defined like this:
typedef struct a { const int a; } A;
I know that this code is valid:
A * foo = malloc(sizeof *foo); // Allocates uninitialized memory with no effective type
memcpy(foo, &(typeof(*foo)){ .a = 42, }, sizeof *foo); // Effectively initialize the value once
(see https://stackoverflow.com/a/79012045/13242312)
But is it still valid with alloca instead of malloc if we want the value to be on the stack instead of the heap ?
Use case: I want a single return path in my function, so I want to define the result variable at the function scope
A A_new(void) {
A * a = alloca(sizeof *a);
if (/* something */) {
memcpy(a, &(typeof(*a)){.a = 1}, sizeof *a);
} else {
memcpy(a, &(typeof(*a)){.a = 2}, sizeof *a);
}
return *a;
}
foois a pointer. It doesn't matter where it points or how that memory was allocated, as long as there's enough bytes available. With that said, what is the use-case for you to useallocainstead of just defining a normal local variable?mallocandallocamakes a difference?alloca()has a local lifetime, consider instead usingA * foo = &(typeof(*foo)){ .a = 42, };orA * foo = &(A){ .a = 42, };which is also good (until the end of the block).alloca()is not part of the standard C library. Posting a use case would be useful to offer good alternatives.A a = { .a = (somecondition) ? 1 : 2, };?