Its quite simple: free de-allocates the memory the pointer is pointing to. BUT: it does NOT change the value of p. So p still holds the address. (free cant change the variable it got hand over since c calls goes by copy, not by reference ....) The undefined behavior results from using the pointer still holding the address while a subsequent malloc can re-use the memory. Therefore its a good practice always set the pointer to NULL directly after freeing it. cheers OJ -----Original-Nachricht----- Betreff: Re: Undefined behavior or not? Datum: 2017-03-10T23:25:42+0100 Von: "Martin Sebor" <msebor@xxxxxxxxx> An: "Segher Boessenkool" <segher@xxxxxxxxxxxxxxxxxxx>, "Liu Hao" <lh_mouse@xxxxxxx> On 03/10/2017 09:12 AM, Segher Boessenkool wrote: > On Fri, Mar 10, 2017 at 11:57:28PM +0800, Liu Hao wrote: >>> So does this mean, that the above C code uses undefined behavior? >> Yes. >> >> 6.2.4 Storage durations of objects >> 1 ... Allocated storage is described in 7.22.3. >> 2 ... The value of a pointer becomes indeterminate when the object it >> points to (or just past) reaches the end of its lifetime. >> >> 7.22.3 Memory management functions >> 1 ... The lifetime of an allocated object extends from the allocation >> until the deallocation. ... > > But a null pointer does not point to an (allocated) object. So the > code has undefined behaviour only if ever the pointer is not a null > pointer? That's right. Same as in: char *p = 0; if (rand () & 1) { char c; p = &c; } if (p) puts ("p i non-null"); else puts (p is null"); Martin