who free's setvbuf buffer?
Posted
by Evan Teran
on Stack Overflow
See other posts from Stack Overflow
or by Evan Teran
Published on 2010-04-19T21:44:53Z
Indexed on
2010/04/19
21:53 UTC
Read the original article
Hit count: 433
So I've been digging into how the stdio portion of libc is implemented and I've come across another question. Looking at man setvbuf
I see the following:
When the first I/O operation occurs on a file, malloc(3) is called, and a buffer is obtained.
This makes sense, your program should have a malloc
in it for I/O unless you actually use it. My gut reaction to this is that libc will clean up its own mess here. Which I can only assume it does because valgrind reports no memory leaks (they could of course do something dirty and not allocate it via malloc
directly... but we'll assume that it literally uses malloc
for now).
But, you can specify your own buffer too...
int main() {
char *p = malloc(100);
setvbuf(stdio, p, _IOFBF, 100);
puts("hello world");
}
Oh no, memory leak! valgrind confirms it. So it seems that whenever stdio allocates a buffer on its own, it will get deleted automatically (at the latest on program exit, but perhaps on stream close). But if you specify the buffer explicitly, then you must clean it up yourself.
There is a catch though. The man page also says this:
You must make sure that the space that buf points to still exists by the time stream is closed, which also happens at program termination. For example, the following is invalid:
Now this is getting interesting for the standard streams. How would one properly clean up a manually allocated buffer for them, since they are closed in program termination? I could imagine a "clean this up when I close flag" inside the file struct, but it get hairy because if I read this right doing something like this:
setvbuf(stdio, 0, _IOFBF, 100);
printf("hello ");
setvbuf(stdio, 0, _IOLBF, 100);
printf("world\n");
would cause 2 allocations by the standard library because of this sentence:
If the argument buf is NULL, only the mode is affected; a new buffer will be allocated on the next read or write operation.
© Stack Overflow or respective owner