[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Basic, but what the hell am I doing wrong here?



Stephen Touset wrote:

>I'm working on a fairly large program for a class, and now every time I
>run it, it segfaults.
>
>I've secluded the part that seems to cause the problems, and wrote a
>small file called test.cc, which contains a minimal implementation fo
>the code that brings up the segfault. It's attached. The code simply
>opens a file then reads it until empty.
>  
>
Yep, you got two problems.

1. You're using a pointer that you haven't pointed anywhere. Repeat
after me:
I will always initialize a pointer to 0 (NULL). I will always set the
pointer to 0 (NULL) after I delete my data.
I will always initialize a pointer to 0 (NULL). I will always set the
pointer to 0 (NULL) after I delete my data.
I will always initialize a pointer to 0 (NULL). I will always set the
pointer to 0 (NULL) after I delete my data.

2. You're trying to read 80 chars in to a space that only holds 1.
(However the segfault is caused by the above problem.)

Try this:
#include <fstream>

using namespace std;

int main(void)
{

    ifstream fin("test.cc");
    char* str = 0;
    str = new char[81]; //80 chars + 1 for null character

    if (!fin.is_open())
    {
        exit(1);
    }

    while (!fin.eof())
    {
        fin.getline(str, 80);
    }

    fin.close();

    //Not really necessary since it's the end of the program, but
    //good practice.
    delete [] str;
    str = 0;

    return 0;

}

HTH,
Brent

BTW, Don't you think this is a better topic for comp.lang.c++ then
debian-users?



Reply to: