In article <kqn30c.u75.ln@192.168.0.1>,
Eirik WS <> wrote:
> Consider the following code:
>
> #include <stdio.h>
> #include <stdlib.h>
>
> typedef struct {
> int x;
> int y;
> } tals;
>
> int main(void) {
> tals *ein, *to;
> ein = malloc(sizeof(tals));
> ein->x = 13;
> free(ein);
> to = malloc(sizeof(tals));
> to->y = to->x - 0;
> printf("%d\n", to->y);
> free(to);
> return 0;
> }
>
> You can see what happens. I declare two pointers to a
> tals structure. I allocate memory for the first, assign its x
> field to a value of 13 and free it.
>
> Then I allocate memory for the second structure and
> assign the value to->x - 0 to it.
>
> On my computer(x86, GNU/Linux), the printf says 13.
> Is this code portable? Should I rely on it preserving the value
> of the free'd structure?
This code invokes undefined behavior by accessing to->x which has an
indeterminate value. In your case, the effect of the undefined behavior
was apparently that to->x held the value that was previously stored into
ein->x which is quite unfortunate. If you had been more lucky then your
program would have crashed; that would have told you immediately that
(1) no, it is not portable at all and (2) no, you can't rely on it, you
can't even be sure that your program doesn't crash immediately.
|