Given this program, strict aliasing rules and type based alias analysis optimization:
#include<stdio.h>
#include<stddef.h>
#include<stdalign.h>
#include<assert.h>
struct thing {
int x;
int y;
};
static_assert(sizeof("hello") < sizeof(struct thing),"buffer can't hold text");
int main() {
alignas(struct thing) char buffer[sizeof(struct thing)] = "hello";
void *ptr = buffer;
struct thing* s = ptr;
s->x = 20;
s->y = 30;
printf("%s",buffer);
return 0;
}
could a conforming compiler decide that the buffer never changes, so it can be placed in read-only segment (or similar) and thus this will print hello? (works as expected in practise)
Perhaps I shall add a motivating example as to why one would want to do this. Say one have created an arena allocator that works fine when passed an initial slab of memory by malloc. No problem, any time we write to memory gotten from this allocator we are changing effective types on first write to the (void*) we get. However if our arena allocator is initialized with a char* gotten from stack memory (say aligned suitably for any type we will write to it), it is a big no no as we would be aliasing the char buffer.
This leads me to feel this is a hole in the language. Why can we not stack allocate suitably aligned untyped (but sized) memory?