Closed marcusnaslund closed 7 years ago
In contrast,
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(0));
int* p = (int*)(rand() % 0xFFFFFFFF);
free(p);
}
segfaults every time.
This puts an uninitialized array on the stack
No, it doesn't. It puts an initialized struct on the stack, which contains a pointer to void.
It's undefined behavior, so really, nothing is "expected".
If you compile with optimizations, the free()
will be elided. with gcc -O2
, this is the x86 generated for your program:
main: # @main
xorl %eax, %eax
retq
Without optimizations, we get:
main: # @main
pushq %rbp
movq %rsp, %rbp
subq $16, %rsp
movq -8(%rbp), %rdi # quadword
callq free
xorl %eax, %eax
addq $16, %rsp
popq %rbp
retq
Since everything is uninitialized, what you have on the stack is what was there before.
If we go out of our way to "pollute" the stack, it's easy to observe a crash:
It puts an initialized struct on the stack, which contains a pointer to void.
Sorry, this is what I meant. The data
pointer is what is uninitialized.
I understand now, I just did not pollute the stack enough to see the problem.
Many thanks.
No problem. The Wonderful World Of UB is always difficult to navigate in...
(This may be the product of something I've misunderstood, or just pure random chance, if so I will close)
Consider the very simple program:
(I know, with GC you wouldn't have to manually
free
, but bear with me)The generated C code for
test
isThis puts an uninitialized array on the stack, where
length
anddata
have garbage values. But the free call never seems to crash, as opposed towhich always crashes. With good reason, of course. But why does freeing an uninitialized ooc array never seem to crash?
(Running gcc 4.9 on ubuntu 14.04.)