c - Does free() set errno? -
if buf
malloc()
allocated char buffer, free(buf)
set/reset errno
?
let's want write buffer file, , free it, don't need more.
let's error policy code return -1 on error.
is proper way write out buffer , error check without leaking memory?
fputs(buf, somefile); free(buf); if (errno) return -1;
or need consider free possibly setting errno, in...
fputs(buf, somefile); if (errno){ free(buf); return -1; } free(buf);
or, horror of horrors,
do { fputs(buf, somefile); int save_errno = errno; free(buf); errno = save_errno; if (errno) return -1; } while(0);
where use of block allows local save_errno exist in various places should need reused.
all of seem depend on whether free() sets errno.
the linux man page free() man page malloc()
, etc. mentions malloc()
setting errno, not free()
.
the gnu c library manual page freeing dynamic memory not mention whether free() sets errno.
so wrote short program force write error see if free() reset errno, , not. i'm wondering if should rely upon result , fact free() essential "of course doesn't set errno."
# see if free() resets errno on bad write #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char **argv) { char * buf = malloc(256); snprintf(buf,256,"%s\n", "hello, world!"); file *badfile; badfile = fopen("/dev/null","r"); fputs(buf, badfile); free(buf); printf("%d\n", errno); printf("%s\n", strerror(errno)); }
posix doesn't define free
set errno
(although posix doesn't forbid it, implementation might - refer @arjunshankar's answer more details). that's not relevant concern.
the way you're checking errors incorrect. should check return value of fputs
, , check if it's smaller 0
. if is, can check errno
find out caused failure, that's optional (and should done before calling further functions).
so, should trick :
int result = fputs(buf, somefile); /* optionally read errno here if result < 0 (before free call) */ free(buf); return (result < 0) ? -1 : 0;
Comments
Post a Comment