问题
I keep getting a read access violation. Here is the code that I have.
class List
{
public:
List();
List(const List ©);
~List();
/*List & operator=(const List &rhs);
Record * headPtr() const;
void setheadptr(Record * const newhead);
bool insertatfront(Record newdata);*/
void importcourselist();
void Loadmasterlist();
void storemasterlist();
Record *makenode(fstream &file);
Record *makenode(ifstream &file);
private:
Record *mHead;
Record *mEnd;
};
List::List()
{
mHead = nullptr;
mEnd = nullptr;
}
void List::storemasterlist()
{
ofstream outfile;
outfile.open("masterlist.txt");
mEnd = mHead;
while (mEnd->getnext()!= nullptr)
{
outfile << mEnd << endl;
mEnd = mEnd->getnext();
}
outfile << mEnd;
}
I'm not exactly sure what is going on but, every time I try to debug it it'll send me to the getter function for my pointer which looks like this:
Record *Record::getnext()
{
return mnext;
}
I believe that my error lies somewhere in my import function. This is where I'm creating the extra empty node.
void List::importcourselist()
{
ifstream infile;
string ptoken;
infile.open("studentlist.csv");
getline(infile, ptoken);
mHead = makenode(infile);
mEnd = mHead;
while (!infile.eof())
{
mEnd->setnext(makenode(infile));
mEnd = mEnd->getnext();
}
infile.close();
}
回答1:
The constant 0xCD is used by Microsoft C++ debug libraries to fill allocated heap blocks. So you can see the pattern 0xCDCDCDCD when you read data from a dynamic heap object which hasn't been initialized by your code.
You didn't show the Record class definition, but I guess your Record::Record constructor fails to set the next pointer to nullptr. When iteration comes to the end of the list you fetch that magic 0xCDCDCDCD value with getnext(). That is an invalid pointer, hence you fail to access the memory at 0xCDCDCDCD with the next getnext() call.
Sources:
- Magic number (programming) at Wikpedia
- Win32 Debug CRT Heap Internals by Andrew Birkett at his www.nobugs.org
- Magic Numbers in Visual C++ (Aug 2009) at Adam Sawicki's asawicki.info
回答2:
This is sort of a guess:
- you call
while(mEnd->getnext() ...)for the loop - then in the body of the loop you call
mEnd->getnext()again, which does not deliver the same result; i.E. it might be past the end already.
来源:https://stackoverflow.com/questions/45205656/read-access-violation-0xcdcdcdcd