我正在阅读glibc-2.19的来源。我发现如果我使用fopen
来获取FILE
的指针,则stdio的缓冲区已经存在。它何时何地分配和初始化?
答案 0 :(得分:0)
我发现如果我使用fopen获取FILE指针,stdio的缓冲区已经存在。
目前尚不清楚您的确切内容或方式。通常情况下,FILE
使用的缓冲区不分配,直到您尝试读取或写入FILE
的内容。
示例:
#include <stdio.h>
int main()
{
FILE *fp = fopen("/etc/passwd", "r");
int c = fgetc(fp);
return 0;
}
gcc -g t.c && gdb -q ./a.out
Reading symbols from ./a.out...done.
(gdb) start
Temporary breakpoint 1 at 0x400535: file t.c, line 5.
Starting program: /tmp/a.out
Temporary breakpoint 1, main () at t.c:5
5 FILE *fp = fopen("/etc/passwd", "r");
(gdb) n
6 int c = fgetc(fp);
(gdb) p *fp
$1 = {
_flags = -72539000,
_IO_read_ptr = 0x0,
_IO_read_end = 0x0,
_IO_read_base = 0x0,
_IO_write_base = 0x0,
_IO_write_ptr = 0x0,
_IO_write_end = 0x0,
_IO_buf_base = 0x0,
_IO_buf_end = 0x0,
_IO_save_base = 0x0,
_IO_backup_base = 0x0,
_IO_save_end = 0x0,
_markers = 0x0,
_chain = 0x7ffff7dd41c0 <_IO_2_1_stderr_>,
_fileno = 3,
_flags2 = 0,
_old_offset = 0,
_cur_column = 0,
_vtable_offset = 0 '\000',
_shortbuf = "",
_lock = 0x6020f0,
_offset = -1,
__pad1 = 0x0,
__pad2 = 0x602100,
__pad3 = 0x0,
__pad4 = 0x0,
__pad5 = 0,
_mode = 0,
_unused2 = '\000' <repeats 19 times>
}
上面你可以清楚地看到,还没有分配任何内部缓冲区:_IO_read_ptr
,_IO_read_end
等。
现在让我们在&fp->_IO_read_ptr
和next
上设置一个观察点:
(gdb) watch -l fp._IO_read_ptr
Hardware watchpoint 3: -location fp._IO_read_ptr
(gdb) next
Hardware watchpoint 3: -location fp._IO_read_ptr
Old value = 0x0
New value = 0x7ffff7ff7000 ""
0x00007ffff7a8f689 in _IO_new_file_underflow (fp=0x602010) at fileops.c:608
608 fileops.c: No such file or directory.
(gdb) bt
#0 0x00007ffff7a8f689 in _IO_new_file_underflow (fp=0x602010) at fileops.c:608
#1 0x00007ffff7a9062e in __GI__IO_default_uflow (fp=0x602010) at genops.c:435
#2 0x00007ffff7a86bae in _IO_getc (fp=0x602010) at getc.c:39
#3 0x00000000004005a4 in main () at t.c:6
现在您可以看到尝试从FILE
读取确实会导致缓冲区在_IO_new_file_underflow
中分配。