Insert into multimap causes segfault - c++

I am working on a project using multimaps inside of my own class, and I have run into a segfault. Here are the parts of my code relating to the issue. I would really appreciate some help. Thanks.
Here is database.h
#include <iostream>
#include <map>
using namespace std;
class database{
public:
database(); // start up the database
int update(string,int); // update it
bool is_word(string); //advises if the word is a word
double prox_mean(string); // finds the average prox
private:
multimap<string,int> *data; // must be pointer
protected:
};
Here is the database.cpp
#include <iostream>
#include <string>
#include <map>
#include <utility>
#include "database.h"
using namespace std;
// start with the constructor
database::database()
{
data = new multimap<string,int>; // allocates new space for the database
}
int database::update(string word,int prox)
{
// add another instance of the word to the database
cout << "test1"<<endl;
data->insert( pair<string,int>(word,prox));
cout << "test2" <<endl;
// need to be able to tell if it is a word
bool isWord = database::is_word(word);
// find the average proximity
double ave = database::prox_mean(word);
// tells the gui to updata
// gui::update(word,ave,isWord); // not finished yet
return 0;
}
Here is test.cpp
#include <iostream>
#include <string>
#include <map>
#include "database.h" //this is my file
using namespace std;
int main()
{
// first test the constructor
database * data;
data->update("trail",3);
data->update("mix",2);
data->update("nut",7);
data->update("and",8);
data->update("trail",8);
data->update("and",3);
data->update("candy",8);
// cout<< (int) data->size()<<endl;
return 0;
}
Thanks very much. It compiles and runs up to cout << "test1" << endl; but segfaults on the next line.
Rusty

You never actually created a database object, just a pointer to nowhere (perhaps you're used to another language).
Try creating one like this database data;
And then change your -> to . to access the members.
Consider obtaining one of the books at The Definitive C++ Book Guide and List as well.

You need to allocate your database before starting to insert data on it.
Change:
database *data;
to:
database *data = new database();
or:
database data;
in main().
EDIT: if you use the latter, change -> to . on the subsequent method calls. Otherwise, remember to delete your data object after using it.

Related

Trying to understand the keyword friend correctly via OOP in c++, coding issues

OK so here's my question, I'm trying to understand the use of friend in C++ with a working example on my PC for reference. I have everything set up in different classes, which are connected to one another with the .h files etc. (I think anyways). Can someone show me where I'm going wrong please? Cause i keep getting compiler errors and I don't understand what it means.
Yes I've researched the C:xxxx errors online, but I can't link the problem to the code I've got... It's obviously wrong! just need a push in the right direction / better understanding of C++... thank you!
//First class
#include <iostream>
#include <string>
using namespace std;
class Tutorial48
{
private:
int var;
int secret = 5;
public:
Tutorial48(int v);
friend class Tutorial48UseFriend;
void PrintVar();
};
// First class .cpp
#include "Tutorial48.h"
Tutorial48::Tutorial48(int v)
{
var = v;
}
void Tutorial48::PrintVar()
{
cout << var << endl;
cout << "Scret variable = " << secret << endl;
}
// Second class, whole point is to demo the friend keyword in C++!
#include "Tutorial48.h"
#include <iostream>
#include <string>
using namespace std;
class Tutorial48UseFriend
{
public:
Tutorial48UseFriend();
void showSecret(Tutorial48 tut48F)
{
// Just trying to increment by 1 so i know it's worked correctly.
tut48F.secret++;
cout << "My new private variabe = " << tut48F.secret << endl;
};
};
// Main function for outputting the whole thing.
#include "Tutorial48.h"
#include "Tutorial48UseFriend.h"
#include <string>
#include <iostream>
int main
{
Tutorial48UseFriend fr;
Tutorial48 t(24);
fr.showSecret(t);
getchar();
return 0;
}
Errors being produced....
Errors
Yeah so that's everything... As i said i'm new to this, so trying to understand it. Thank you to anyone for help in advance, cheers guys.
P.s. I do kind of understand the concepts of friend in c++ how it's used to access private variables of other classes etc. but i have no idea how to code it properly...
You should define the constructor of Tutorial48UseFriend like:
Tutorial48UseFriend(){}
and also pass Tutorial48 object by reference (by using '&'), and instead of making the function void make it return an int and then print it later, so:
int showSecret(Tutorial48& tut48F)
{
return ++tut48F.secret;
}

"Process terminated with status -1073741819" simple program with vector

for some reason I get the "Process terminated with status -1073741819" error whenever I run my program, I've read that some people get this error because of something wrong with code-blocks/the compiler, i just wanted to know if there is anything wrong with my code before i go reinstalling compilers and such. I'm using code::blocks and the GNU GCC compiler.
my code creates a vector which stores 40 working hours in a week, and a vector inside that vector which stores letters representing the 5 people available in those hours.
Schedule.cpp:
#include <iostream>
#include "Schedule.h"
#include <vector>
#include <string>
using namespace std;
/// Creates a Vector which holds 40 items (each hour in the week)
/// each item has 5 values ( J A P M K or X, will intialize as J A P M K)
vector< vector<string> > week(40, vector<string> (5));
Schedule::Schedule(){
for (int i = 0; i<40; i++){
week[i][0] = 'J';
week[i][1] = 'A';
week[i][2] = 'P';
week[i][3] = 'M';
week[i][4] = 'K';
}
// test
cout << week[1][3] << endl;
}
header file:
#ifndef SCHEDULE_H
#define SCHEDULE_H
#include <vector>
#include <string>
using namespace std;
class Schedule
{
public:
Schedule();
protected:
private:
vector< vector<string> > week;
};
#endif // SCHEDULE_H
main.cpp:
#include <iostream>
#include "Schedule.h"
#include <vector>
#include <string>
using namespace std;
int main()
{
Schedule theWeek;
}
This is not a copiler bug.
You are getting a memory fault in your constructor.
There are several things wrong with your code, for example in your cpp you declare a global vector week which then is hiden in the constructor since the constructor will access Schedule::week .
Your cpp should be something like :
// comment out the global declaration of a vector week ...
// you want a vector for each object instantiation, not a shared vector between all Schedule objects
// vector< vector<string> > week(40, vector<string> (5));
Schedule::Schedule()
{
for (int i=0;i<40;i++)
{
vector<string> stringValues;
stringValues.push_back("J");
stringValues.push_back("A");
stringValues.push_back("P");
stringValues.push_back("M");
stringValues.push_back("K");
week.push_back(stringValues);
}
}
You get the memory fault in your code when you try to access your week vector for the first time :
week[i][0] = 'J' ;
At the moment you call that line of code, your Schedule::week vector has 0 elements inside it (so week[i] is already a fault).

Class does not name a type error

I have the following code in a project:
#ifndef MAP_H
#define MAP_H
#include <string>
#include "MapCell.h"
using namespace std;
class Map{
public:
Map();
Map(int, int);
Map(string);
virtual ~Map();
private:
int grid_size;
MapCell * grid;
};
#endif
When I go to compile, I get the error "error: 'MapCell' does not name a type" yet when I comment out MapCell * grid and run this next block of code from main:
#include <iostream>
#include <cstdlib>
#include "MapCell.h"
using namespace std;
int main() {
MapCell * test_var;
test_var = new MapCell();
delete test_var;
cout << "Press enter to end process...";
cin.get();
cin.get();
return 0;
}
everything works just fine. I know my MapCell.h and .cpp files are in the right places and I'm guessing the compiler can see them since it works from main. I read around some other questions and most answers seem to point to either syntax errors or forward declarations which don't really fit here (unless I'm overlooking something)
Any ideas on what's going on here?
chris and greatwolf led me to the solution that fixed the problem. I needed to forward declare my MapCell class for the compiler to be able to link to the whole class.

C++ Using RapidXml parsing XML File, Wrapper Class, parse_error expect >

I'm trying to use the RapidXML to parse my XML file. And I did it following the example here. Instead of doing the parsing in the main function, I wrote a wrapper class called XMLParser to do the parsing job. And this really gives me a headache.
The XMLParser.hpp:
#include <iostream>
#include <string>
#include <stdio.h>
#include <vector>
#include "rapidxml/rapidxml.hpp"
using namespace std;
using namespace rapidxml;
class XMLParser {
public:
XMLParser() {};
XMLParser(const std::string &xmlString): xmlCharVector(xmlString.begin(), xmlString.end())
{
//xmlCharVector.push_back('\0');
parseXML();
}
XMLParser(const std::vector<char> &_xmlVector):xmlCharVector(_xmlVector)
{
/* xmlCharVector.push_back('\0'); */ // already done in main.cpp
if (xmlCharVector != _xmlVector) //And it turns out they're the same....
std::cout << "The two vectors are not equal" << std::endl;
else
std::cout << "They are the same" << std::endl;
parseXML();
}
private:
std::vector<char> xmlCharVector;
rapidxml::xml_document<> doc;
void parseXML();
};
The XMLParser.cpp:
#include "XMLParser.hpp"
using namespace std;
using namespace rapidxml;
void XMLParser::parseXML()
{
doc.parse<0>(&xmlCharVector[0]);
}
And here is the main.cpp:
#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
#include <fstream>
#include "XMLParser.hpp"
using namespace std;
using namespace rapidxml;
int main(int argc, char **argv)
{
xml_document<> doc;
xml_node<> *root_node;
ifstream theFile("beer.xml");
vector<char> buffer((istreambuf_iterator<char>(theFile)), istreambuf_iterator<char>());
buffer.push_back('\0');
doc.parse<0>(&buffer[0]);
root_node = doc.first_node("MyBeerJournal");
xml_node<> *engine = root_node->first_node("Brewery");
//The above code works pretty well, and I can get the element I want in XML file.
//The problem occurs when I tried to use the XMLParser
XMLParser xmlParser(buffer);
return 0;
}
The parsing process in the main function works pretty well. But when I tried to use the function in my wrapper class parseXML(), then error occured:
terminate called after throwing an instance of 'rapidxml::parse_error'
what(): expected >
Abort (core dumped)
Originally I have other code in this function, but I commented them all, and find that even with the single line doc.parse<0>(&xmlCharVector[0]);. Why it works well in main.cpp while not in the wrapper class? I really can't figure it out. Could anybody help me?
I've found out the reason... This stupid problem really takes me a long time to debug. I'm writing it here so that anyone ran into it (hope not) could save his time. The problem lies exactly in the code doc.parse<0>(&buffer[0]) in the main function. Before executing this line of code, the buffer(type of vector<char>) is like this: (by printing the vector to console)
<MyBeerJournal>
<Brewery name="Founders Brewing Company" location="Grand Rapids, MI">
<Beer name="Centennial" description="IPA" rating="A+" dateSampled="01/02/2011">
"What an excellent IPA. This is the most delicious beer I have ever tasted!"
</Beer>
</Brewery>
.....
.....
</MyBeerJournal>
It's the same with original xml file. After executing the above code, the buffer(type of vector<char>) becomes something like this:
<MyBeerJournal
<Breweryname"Founders Brewing Company location"Grand Rapids, MI>
<Beername"Centennial description"IPA rating"A+ dateSampled"01/02/2011>
"What an excellent IPA. This is the most delicious beer I have ever tasted!"
/Beer>
</Brewery>
As you can see, some angel brackets disappeared. and some other things like double quote has also been changed. So the wrapper class constructor copied the modified "xml buffer", and this not well formatted xml vector will certainly cause the second doc.parse<0>(&xmlCharVector[0]); in the wrapper class to fail. I don't know why the library writer needs to modify the char vector passed in, because the subsequent xml analysis is not relevant to the original char vector once the DOC has been created.

Stacks and queues are giving errors in Dev-C++

I was given and assignment to develop a cellphone simulation, part of the requirements includes me using a queue to store the phone numbers that come from a txt file to simulate getting called. I have reviewed over and over again and including #include but the error message telling me "Queue" undeclared still shows up. I am using Bloodsehd Dev-C++, and I have included a sample I used to test the queue, if it is just the program not having the right information, any help would be appreciated. I have checked other sites most say add a #include or a #include neither seemed to solve the problem.
#include <queue>
#include <deque>
#include <iostream>
#include <fstream>
using namespace std;
class cell
{
public:
cell();
~cell();
void upload( string item );//Insert in order
void printnew();//Print call just recieved
void printlater();//Print calls for later
int Front(); //returns front element
int Rear(); //returns rear element
bool Empty();
private:
};
int main()
{
Queue Q;
Q.Enqueue(54);
cout << Q.front();
system("Pause");
return 0;
}
To use STL queue, you need to:
#include <queue> // include necessary header
std::queue<int> q; // initialize queue container with type int
q.push(54); // add element to queue
std::cout << q.front() << std::endl; // access the head of queue
checkout std::queue reference http://en.cppreference.com/w/cpp/container/queue
If you want to use C++ Standard Library queue, you must declare it as
queue<int> Q;
Q.push(54);
cout << Q.front();
queue is supposed to be lowercase.
You can find info on using the queue here:
http://www.cplusplus.com/reference/queue/queue/queue/