使用fgets读取文件时出现段错误

时间:2014-10-29 19:32:40

标签: c gdb

使用fgets()时出现段错误。有没有人知道哪里可能出错?谢谢。 这是我的代码部分:

char buf[1024]="";
char str[32];
char line[32];

in = fopen(argv[1], "r");

while(fgets (line, sizeof(line), in) != NULL){          
        zero_pad(line, str);  // padding 0s to the line
        strcat(buf, str);
        printf("\nBuffer: %s\n", buf);
}

这是zero_pad函数:(它只是查找位数,如果字符串的长度小于位数,则在前面附加0)

void zero_pad(char line[], char res[]){
   int num_bits, i;
   char *tmp;
   char *bin_str;
   if(line[strlen(line)-1]=='\n')  line[strlen(line)-1]='\0';
   //split by space
   tmp = strtok(line, " ");
   strcpy(bin_str, tmp);
   tmp = strtok(NULL, " ");
   num_bits = atoi(tmp);

   if(strlen(bin_str) < num_bits) {
     char t[32]="";
     for(i=0; i< (num_bits-strlen(bin_str)); i++)
          t[i] = '0';

     strcat(t, bin_str);
     strcpy(res, t);
   }
   else
     strcpy(res, line);   
}

在GDB中,我收到了以下错误消息:

Program received signal SIGSEGV, Segmentation fault.
__GI___libc_free (mem=0x7ffff7eca000) at malloc.c:2929
2929    malloc.c: No such file or directory.

(gdb) bt
#0  __GI___libc_free (mem=0x7ffff7eca000) at malloc.c:2929
#1  0x00007ffff7a8ff5e in _IO_free_backup_area (fp=0x603250) at genops.c:209
#2  __GI___uflow (fp=0x603250) at genops.c:388
#3  0x00007ffff7a83dc4 in __GI__IO_getline_info (fp=0x603250, 
    buf=0x7fffffffdf60 "1111", n=31, delim=10, extract_delim=1, eof=0x0)
    at iogetline.c:69
#4  0x00007ffff7a82d46 in _IO_fgets (buf=0x7fffffffdf60 "1111", n=0, 
    fp=0x603250) at iofgets.c:56
#5  0x0000000000400b8d in main ()

我也试过ltrace。

以下是最后几行:

putchar(65, 0x7fffd69cb460, 0, 0x7fa52aa5fa50)   = 65
printf("\nBuffer: %s\n", "0001000100010000000000001111"A
Buffer: 0001000100010000000000001111
) = 38
putchar(67, 0x7fffffda, 0x7fa52ad809e0, 37)      = 67
fgets( <no return ...>
--- SIGSEGV (Segmentation fault) ---
+++ killed by SIGSEGV +++

1 个答案:

答案 0 :(得分:2)

下面:

void zero_pad(char line[], char res[]){
   int num_bits, i;
   char *tmp;
   char *bin_str;
   if(line[strlen(line)-1]=='\n')  line[strlen(line)-1]='\0';
   //split by space
   tmp = strtok(line, " ");
   strcpy(bin_str, tmp);

...您的strcpy()正在尝试将tmp的内容复制到未初始化指针bin_str指向的位置。

如果您愿意假设单词的最大长度(基于,可能是main()函数中声明的数组大小),那么您可以这样声明:

char bin_str[32];