分段故障调用setvbuf

时间:2013-09-23 07:46:20

标签: c cygwin stdio

我正在尝试使用setvbuf的基本程序:

int main(int argc, char **argv) {

    FILE * fp;
    char buffer[1024];

    fp = fopen("~/my.txt", "w");

    setvbuf(fp, buffer, _IOFBF, sizeof(buffer));

    return EXIT_SUCCESS;
}

当我运行程序时,我在setvbuf上遇到了分段错误:

Breakpoint 1, main (argc=0, argv=0x20) at ../my.c:13
13      int main(int argc, char **argv) {
(gdb) n
18              fp = fopen("~/my.txt", "w");
(gdb) n
20              setvbuf(fp, buffer, _IOFBF, sizeof(buffer));
(gdb) n

Program received signal SIGSEGV, Segmentation fault.
0x0000000000000000 in ?? ()

我的环境是:

$ uname -a
CYGWIN_NT-6.1 myhost 1.7.25(0.270/5/3) 2013-08-31 20:37 x86_64 Cygwin
$ gcc --version
gcc (GCC) 4.8.1

1 个答案:

答案 0 :(得分:1)

根据Oli's commentPaul R's comment的通知,我添加了相应的错误处理:

fp = fopen("~/my.txt", "w");
if (fp == NULL)
  {
    perror ("The following error occurred");
    printf( "Value of errno: %d\n", errno );
    return EXIT_FAILURE;
  }

输出结果为:

The following error occurred: No such file or directory
Value of errno: 2

将文件路径修复为完整路径后,对setvbuf的调用成功。