Mail Archives: djgpp/1997/12/03/19:58:05
At 07:32 12/3/1997 GMT, E. Schmidt wrote:
>
>Hallo World!
>
>1. How to define user function with variable
> number of arguments? I simply want(ed) to
> define my error handler printing some formatted message
> and making some other things like closing files...
You use the `stdarg' macros, which are part of ANSI C. (va_list, va_arg,
etc.) These were somehow omitted from the libc documentation. I wrote a
replacement doc and will send you a copy under separate cover. It's a fairly
simple scheme.
>
>2. How to close the file, if I don't know if it is opened or closed?
> Only file variable FILE * fp; is achivable.
The best way is to keep track, and only close it if it's actually opened.
One way might be to set fp=NULL when you close it, and then check whether
it's NULL before you try again. You can also use this scheme, which I think
should work:
void close_if_open(FILE *fp)
{
fp = freopen("/dev/null", "r", fp);
if (fp) fclose(fp);
}
`freopen()' is supposed to close the file if it's open, then reopen that
stream onto some other file. I use "/dev/null" because, on DJGPP and Unix,
it's always there.
The FILE struct probably has a flag which says whether the file is open, but
this is nonportable. Also be sure that fp is a real open or closed stream,
and not just a random pointer.
>
>3. Is it important in C to free the memory in the inverse
> allocation order ?
> p1=malloc(100);
> p2=malloc(200);
> ...
> free(p2);
> free(p1);
> What happens with pieces of memory which are set free in "wrong" order?
No problems. `malloc()'s and `free()'s can be called in any order, as long
as you only `free' pointers obtained from `malloc'.
> For above example
> free(p1);
> p1=malloc(50);
> Would these 50 bytes be allocated in the memory of previous malloc(100) ?
All I can say is: maybe. `malloc' can do it any way it wants. If it finds
that convenient, it might, or it might not. It may just as easily allocate
it somewhere completely different. Bottom line: DON'T count on it.
Hope this helps.
Nate Eldredge
eldredge AT ap DOT net
- Raw text -