segmentation fault with fgets

Jul 1, 2009 at 1:59am
Hi all, I'm completely stuck..
I have a program which reads integers (there are 65536 integers) from one file, and adds them into the Bloom filter. And then it reads another file (with a larger set of integers), and checks the existence of each element in the Bloom filter created in the first step. Here is the code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <string>
#include <iostream>
#include <fstream>
#include "GeneralHashFunctions.h"
#include "falsetest.h"
using namespace std;
int main()
{
int outRes=0;
bfilter BF(BLOOMFILTER_NUMOFHASH, BLOOMFILTER_BITS_SIZE, &outRes);
FILE* pns;
pns = fopen ("pns" , "r");
unsigned int key;
char buffer[16];
while (!feof(pns)) {
        fgets (buffer, 16, pns);
        sscanf (buffer, "%u", &key);
        BF.addmember((char*) &key, sizeof(key));
}
fclose(pns);
int counter = 0;
int counter2=0;
FILE* in_file;
in_file = fopen ("list" , "r");
setvbuf (in_file, NULL , _IOFBF , 4096 );
while (!feof(in_file)) {
        counter2++;
        fgets (buffer, 16, in_file);
        sscanf (buffer, "%u", &key);
        if (BF.isMember((char*) &key, sizeof(key)))
                counter++;
}
BF.~bfilter();
cout<<"Positives= "<<counter<<"\n";
cout<<"Total= "<<counter2<<"\n";
cout<<"False positives= "<<counter-65535<<"\n";
fclose(in_file);
return 0;
}

when I compile and run it, GDB says:

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

And here is the output of backtrace full:
(gdb) backtrace full
#0 0x00000000 in ?? ()
No symbol table info available.
#1 0xf7d3f144 in __uflow () from /lib/libc.so.6
No symbol table info available.
#2 0xf7d325b6 in _IO_getline_info () from /lib/libc.so.6
No symbol table info available.
#3 0xf7d32501 in _IO_getline () from /lib/libc.so.6
No symbol table info available.
#4 0xf7d313cd in fgets () from /lib/libc.so.6
No symbol table info available.
#5 0x08048d86 in main () at falsetest.cpp:16
outRes = 1
BF = {m_bf = 0x804d008 "", m_numHashFns = 3, m_logSize = 18, m_bfBitSize = 262144, m_initialized = 1, byteSize = 1, m_debug = 0}
pns = (FILE *) 0x804d018
key = 3029799107
buffer = "3029799107\n\0008\215╛Ъ"
counter = 134529012
counter2 = -5468808
in_file = (FILE *) 0x804a0d9
(gdb)

One more thing, I found that it reads up to 371 integers from the first file ('pns'), and then segfaults.
Could anyone help me with this problem?
Last edited on Jul 1, 2009 at 2:30am
Jul 1, 2009 at 11:40am
My first concern is that buffer is not null terminated. But why don't you

fscanf( pns, "%u", &key );

instead of reading in a string and then converting? (Or better yet, use ifstream).

Just looking at the rest of your code, line 33 is bad. The object's destructor will be run automatically when main returns.

Topic archived. No new replies allowed.