tags:

views:

58

answers:

2
struct Movie
{
    char* date;
    char* title;
    char* rating;
    int runtime;
};

typedef Movie* moviePtr;
moviePtr tempDB;

bool doStuff()
{
//... snip .,,
    tempDB = new Movie[tempC];
    int i;

    ifs >> temp;
    while(ifs.good() && i < tempC)
    {
        tempDB[i].date = new char[strlen(temp)+1];
        strcpy(tempDB[i].date, temp);
//... snip ...

}

When I run that, I get a segmentation fault (on line tempDB[i].date = new char[strlen(temp)+1]; I debugged it)

tempC is how big the array should be, read from the file.

What have I done wrong :(

+1  A: 

You did not initialize i to 0, or whatever you want to start indexing at.

Another note, in case of errors like seg-fault use Valgrind [valgrind.org] -- it helps spot the error in seconds. In your case an out of index memory access -- these are things Valgrind specializes in detecting.

Fanatic23
Gosh, I'm stupid! :) Thanks.
Johnny
+3  A: 

You never initialize i so at the time you check it for i < tempC and then use it for tempDB[i], i could be worth anything at all -- say -929373, leading to addressing completely outside of your process boundaries (if you're lucky, because that will at least immediately produce an error -- if you're unlucky you'll end up destroying data randomly and producing horrible, impossible-to-debug mistakes at some much later point).

Use int i = 0; instead, to avoid the curse of the uninitialized variable!-)

Alex Martelli