Freeing the same memory twice will result in undefined behaviour, as will writing to memory which has been freed (see the strcpy
).
The C Standard defines Undefined Behaviour in Section §1.3.12 as
behaviour, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements [3].
Undefined behaviour may also be expected when this International Standard omits the description of any explicit definition of behavior.
(3) = permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or with- out the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).
As to what's happening I would guess the following:
You free y
You then strcpy
over what was once y
which may corrupt the heap; this itself is unlikely to segfault, but might (see above)
You then allocate z
, which uses the possibly corrupted heap, and may segfault or misallocate the memory (i.e. return an address which cannot be used).
You then strcpy
into a possibly misallocated bit of memory and thus may segfault.
You then free y
again, with a heap which is possibly corrupt, which may segfault etc.
If you really want to know, use debug libc
and gdb
to find out.