hi guys im trying to transfer an older code from C to C++ for an assignment…. i have to implement a linked list by hand so I cannot use STL containers otherwise i’d already be done with this….
here’s my linked list:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct Video {
char video_name[1024]; // video name
int ranking; // Number of viewer hits
char url[1024]; // URL
Video *next; // pointer to Video structure
} *head = NULL; // EMPTY linked list
here is the read-in code:
void load()
{
struct Video *temp;
temp = (Video*)malloc(sizeof(Video)); //allocate space for node
temp = head;
ifstream myfile ("Ranking.dbm");
if (myfile.is_open())
{
string line;
while ( myfile.good() )
{
myfile.getline(temp->video_name,1024);
myfile >> temp->ranking;
getline(myfile, line); // need to skip 'ranking's
// unread new-line
myfile.getline(temp->url,1024);
temp = temp->next;
}
head = NULL;
myfile.close();
}
else cout << "Unable to open file";
return ;
}
it is reading from a text file Ranking.dbm which looks like this:
bagheera
20
bagheera.com
sushi
60
sushi.com
wicket
99
wicket.com
teek
100
teek.com
basically each set of 3 lines should load into a Video structure which will be a new node in the linked list.
due to circustances beyond my control i am using XCode for this project. my question is why am I getting this error. I thought EXC_BAD_ACCESS was primarily an Objective-C error…?
In your load() function, you allocate a single node, read data to fill in the node, then assign
temp = temp->next. However,temp->nextis not initialized, so likely points to a random address.