Thanks Rich ! I was thinking in terms of file descriptors which is only integers and not whole data structures. Sorry for wasting your time. BTW Musl is really awesome ! On Wed, Oct 24, 2012 at 11:25 PM, Rich Felker wrote: > On Wed, Oct 24, 2012 at 11:22:13PM +0200, Paul Schutte wrote: > > Hi, > > > > It is not my code, but I can not see why it is invalid. > > C99 7.19.3 Files > > ¶4. A file may be disassociated from a controlling stream by > closing the file. Output streams are flushed (any unwritten buffer > contents are transmitted to the host environment) before the > stream is disassociated from the file. The value of a pointer to a > FILE object is indeterminate after the associated file is closed > (including the standard text streams). Whether a file of zero > length (on which no characters have been written by an output > stream) actually exists is implementation-defined. > > Since the value of the pointer-to-FILE is indeterminate after fclose, > any use of it results in undefined behavior. > > The error you've encountered is analogous to the error of calling > free() on memory obtained by malloc(), then later calling realloc() on > the already-freed pointer to try to get it back. This is not the > purpose of realloc (or freopen), and fundamentally cannot work in > general, since the pointed-to memory could already have been reclaimed > for another use. In both cases (realloc and reopen), the function must > be used on an object that is still valid, not one which has already > been closed/freed. > > The fact that it happens to work on glibc is purely luck (good or bad > luck, depending on your perspective). This is the nature of undefined > behavior - it can lead to your program doing what you wanted it to, > even though the program is wrong. > > Rich >