Take the 2-minute tour ×
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 :(

share|improve this question
Why aren't you using std::string and std::vector? –  GManNickG Sep 12 '10 at 4:51
We can't use them, my prof. said so :( I've tried in the past. –  Johnny Sep 12 '10 at 4:53
Strings makes life so much easier!!! –  Johnny Sep 12 '10 at 4:54
What type is temp? You perhaps should try breaking up that expression to determine if it's the strlen(temp) call that's crashing. –  jamesdlin Sep 12 '10 at 4:55
Kindly tell your professor he's an idiot. Your best bet would be to re-make a simple string and vector class yourself and use those. You should always separate resource usage from resource management. (Right now you're trying to do both.) It's not only easier, but safer, cleaner, and more elegant. –  GManNickG Sep 12 '10 at 4:56

2 Answers 2

up vote 1 down vote accepted

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.

share|improve this answer
Gosh, I'm stupid! :) Thanks. –  Johnny Sep 12 '10 at 4:59

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!-)

share|improve this answer

Your Answer


