Is this valid C code without undefined behaviour?
int main(){
int a;
memset(&a, 5, sizeof(int));
return a;
}
I'm assuming this is equal to just doing int a = 5
.
I'm trying to understand if just declaring a variable in the above example (without defining it) is enough to put it on the stack.
Is this valid C code without undefined behaviour?
Yes – Once the a
variable has been declared in a given scope (like a function or other { ... }
delimited block), it is valid to take its address and access the variable using that address within that scope (as your memset
call does). An attempt to use that address when that scope has ended (i.e. is no longer 'active') will cause undefined behaviour; for example, the following is UB:
int main()
{
int* p;
{ // New scope ...
int a;
p = &a; // Pointer to "a" is valid HERE
} // The scope of "a" (and its 'lifetime') ends here
memset(p, 5, sizeof(int)); // INVALID: "p" now points to a dead (invalid) variable
}
However, there's a major caveat in your code sample …
I'm assuming this is equal to just doing int a = 5.
There's the rub: It's assigning 5
to each component byte of the a
variable, so it's doing this (assuming a 4-byte int
):
int a = 0x05050505;
Which is the same as:
int a = 84215045;