TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: KALLE SOIHA
from: DARIN MCBRIDE
date: 1998-04-18 15:36:00
subject: Re: free`ing memory

> fopen() is not a memory allocation function. It is a file opening
> function. Its compliment is fclose(). You cannot use free() on it.
 KS> Oh yes you can. fopen() (in addition to some other, file-related magic) 
 KS> does a malloc() for a struct that is used in 
 KS> conjunction with the other functions of the f*-family 
 KS> to do stream I/O. FILE is just typedef'd to this 
 KS> struct. When you pass a FILE pointer to fclose(), it 
 KS> calls free() to the pointer after doing all other 
 KS> relevant magic (such as flushing the buffers etc). The 
 KS> return value of fopen() is actually the return value of 
 KS> the malloc() that fopen() calls to allocate the space 
 KS> for the FILE struct. Because of this, it can also be free()d.
Not necessarily.
1. No one says that the FILE* returned by fopen needs to be on the heap.  It 
may be a pointer into a static structure.
2. No one says that the FILE* returned by fopen needs to be the head of the 
memory block allocated.  It could be allocated on the heap as a member of:
typedef struct _file_list
{
  struct _file_list* prev;
  struct _file_list* next;
  FILE               data;
} _FILE_LIST;
fopen would thus return a pointer to data.  fclose would (and could - it's 
the library which is inherently non-portable!) then subtract 
2*sizeof(_FILE_LIST*) from the pointer and cast to _FILE_LIST* before 
free'ing it.
Of course, if data was first, its address would be the same as the beginning 
of the block, and could be free'd - no one said it has to be, though.
3. No one says that the FILE* returned by fopen needs to be on the same heap 
as the one malloc uses.  There could be an _internal_malloc that allocates 
from a "private" memory store.  This would be memory that free wouldn't be 
able to handle, but _internal_free could.  These two may do basically the 
same thing, but _internal_malloc may be really _filestream_malloc which may 
be optimized for FILE's or even _FILE_LIST's.
Of these three, I suspect #2 would be right more often than the other two.  
But all three would still be ANSI-C-standard-compliant.
---
---------------
* Origin: Tanktalus' Tower BBS (1:250/102)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.