iEclipse
iEclipse

Reputation: 13

Program crashes when running this function

I'm having trouble with wrapping my head around pointers, and using pointers in structs. To start, I don't know if I am using the pointer properly in the struct. Additionally, when I run my program, it seems to crash when it reaches readRecords, so there must be something wrong with it. Since I don't quite know how to use pointers very well, I am probably doing something wrong here... I just don't know what. Is there some way that I can edit this function so that I don't get crashes? Also, I have to keep these functions, as they are part of my project requirements.

struct testScores
{
    string name;
    string idNum;
    int testNum;
    int *tests;    // This is supposed to be a dynamically allocated array
    double average;
    char grade;
};

[...]

void arrStruct(testScores*& sPtr)
{
    sPtr = new testScores[];
}

void readRecords(ifstream& data, int record, testScores*& sPtr)
{
    for (int count = 0; count < record; count++)
    {
        data >> sPtr[count].name;
        data >> sPtr[count].idNum;
        data >> sPtr[count].testNum;
        sPtr[count].tests = new int[sPtr[count].testNum];   // tests is dynamically allocated (?)
        for (int tCount = 0; tCount < sPtr[count].testNum; tCount++)
            data >> sPtr[count].tests[tCount];
    }
}

Upvotes: 0

Views: 72

Answers (1)

etheranger
etheranger

Reputation: 1273

sPtr = new testScores[];

This appears to be illegal syntax - array new requires a subscript to know how much space to allocate. Usually this is at least 1, in your case the compiler probably interprets this as new testScores[0] which does return a valid pointer, but without allocating any memory from the heap.

Of course any subsequent access to memory pointed to by sPtr is out-of-bounds and causes undefined behaviour (in your case a crash).

Upvotes: 1

Related Questions