Why is my setter method producing a bad access error - c++

Bad access means that i am trying to access memory that doesn't exists I have tried and tried to allocate memory for this class, but have failed everywhere. I do not know where the error is actual coming from. It only tells me that my setter method is when the program crashes. In the setFName() method is where the error occurs. But in the main method is where it actually occurrs.
nurse.hpp
#ifndef Nurse_hpp
#define Nurse_hpp
#include <stdio.h>
#include <string>
#include <stdlib.h>
using namespace std;
class nurse{
private:
string firstName;
public:
nurse() {
firstName = "jim";
}
string getFName() {return firstName;}
void setFName(string fName) {firstName = fName;} // Thread 1: bad access 0x0
};
#endif /* Nurse_hpp */
here is where the error is actually happening
main.cpp
#include <cstdint> // ::std::uint64_t type
#include <cstddef> // ::std::size_t type
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include "nurseHolder.hpp"
using namespace std;
nurseHolder *l = new nurseHolder();
int main() {
return 0;
}
and finally here is the class that is causing the issue
nurseHolder.hpp
#ifndef Nurses_hpp
#define Nurses_hpp
#include <stdio.h>
#include <vector>
#include <stdlib.h>
#include "Nurse.cpp"
using namespace std;
class nurseHolder{
private:
int nurse_cnt;
int nurse_cap;
vector<nurse> nurse_list;
public:
nurseHolder() {
nurse_cnt = 0;
nurse_cap = 10;
for(int i= 0; i < 11; i++){
nurse_list[i].setFName("na");
}
}
vector<nurse> &getNurseList() { return nurse_list;}
};
#endif /* Nurses_hpp */
I tried to make this compact as possible sorry if its a lot of code.
here is what I changed to make the code work:
nurseHolder() {
nurse_cnt = 0;
nurse_cap = 10;
for(int i= 0; i < 11; i++){
nurse l;
nurse_list.pushback(l);
}
}
Is this a correct way to do this?

Your vector nurse_list has size 0. So you cannot use [] operator to set names.
There are two ways you can correct this:
Set an initial size to the vector and use [] to set names.
Use push_back to add elements to the vector.
First method.
nurse_list.resize(noOfTotalNurses).
nurse_list[i].setFName("name");
Second method.
nurse tNurse; //local nurse object
tNurse.setFName("name");
nurse_list.push_back(tNurse);

Related

How to declare a <vector> object and use push_back inside a class?

I'm trying to build a class named "Tombola" which should contain as private variable an empty vector. This should be filled at runtime through the class member Tombola.estrai(), which generates a random number and insert it inside the vector named "order" by the method order.push_back(number). This is the class definition in the tombola.h header:
#ifndef TOMBOLA_H
#define TOMBOLA_H
#include <cstdlib>
#include <vector>
using namespace std;
class Tombola {
private:
bool on_off[90];
int tabellone[9][10];
int x_max = 9;
int y_max = 10;
vector<int> order;
public:
Tombola();
~Tombola();
void nuovo();
int estrai();
bool completato();
void stampa();
void stampa_tab();
};
#endif
And this is the implementation of constructor/destructor and Tombola::estrai() inside tombola.cc:
#include "tombola.h"
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <vector>
#include <iostream>
using namespace std;
Tombola::Tombola () {
vector<int> ord;
order = ord;
int z=1;
for(int i=0;i<90;i++) {
on_off[i] = false;
}
for(int j=0;j<=x_max;j++) {
for (int k=0;k<=y_max;k++) {
tabellone[j][k] = z;
z++;
}
}
}
Tombola::~Tombola() {
cout << "Tombola is destroyed" << endl;
}
int Tombola::estrai() {
srand(time(NULL));
int estrazione = int(ceil(rand()/double(RAND_MAX)*90));
on_off[estrazione]==true;
order.push_back(estrazione);
return order.back();
}
and this is the call to the method in the main.cpp file:
#include "tombola.h"
#include <cstdlib>
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
int main () {
Tombola natale;
cout << natale.estrai();
}
When I compile the program everything goes fine, but when I execute the main I get a segmentation fault error which seems to be due to some sort of allocation error when trying to store the item inside the order vector, as reported by the debugger. Could someone explain to me how to solve the error and why the error occours? Thank you.
The reason of segmentation fault is in the constructor. You have to change for(int j=0;j<=x_max;j++) to for(int j=0;j<x_max;j++) in order not to cross the bounds of the array.
for(int j=0;j<x_max;j++) {
for (int k=0;k<y_max;k++) {
tabellone[j][k] = z;
z++;
}
}
However, there are also some minor issues in the code that are worth being mentioned
declaring default-initialized ord vector and assigning it to order is pointless because order is already default-initialized.(See member initializer list for more information).
using namespace std; in a header file is a terrible idea, because if you had a large codebase, and had multiple source files where you want to include that header, everywhere the using statement will be applied, which probably is not desired.

Using unordered_multimap with a struct data type

I need to define an unordered multimap which holds a key of type int and a value of type "nod".
Nod.h
#pragma once
#include <iostream>
struct nod {
int stare[100], pathManhattan, depth;
nod* nodParinte;
char actiune;
nod();
void Citire(int n);
void Init();
};
Nod.cpp
#include "Nod.h"
#include "ConsoleApplication1.cpp"
nod::nod()
{
pathManhattan = 0;
depth = 0;
nodParinte = NULL;
}
void nod::Citire(int n)
{
for (int i = 0; i < n*n; i++)
{
std::cin >> stare[i];
}
}
void nod::Init()
{
theExplored.insert({ pathManhattan + depth, this });
}
The problems is the Init function. I don't know how to make it work.
ConsoleApplication1.cpp
#include <iostream>
#include <string>
#include <unordered_map>
#include "Nod.h"
std::unordered_multimap<int, nod> theExplored;
std::unordered_multimap<int, nod> theFrontier;
int main()
{
return 0;
}
In my mind it should work, because every nod would have an init function which inserts the node it is used on in theExplored, but I think I might not understood unordered_multimap correctly.
Is my logic flawed? If so, how should I create a Hash table (AFAIK unordered_multimap is basically a hash table) with the key int and the value of type nod?
Also, how can I make a function in the struct so that node gets inserted into the hash table?
Thanks.
I think you need to create a header file for the map definitions in your application source ConsoleApplication1.cpp. You can't just #include the source code as that will give you multiple definitions of your maps.
You can do this, create ConsoleApplication1.h:
#pragma once
#include <unordered_map>
#include "Nod.h"
extern std::unordered_multimap<int, nod> theExplored;
extern std::unordered_multimap<int, nod> theFrontier;
Notice the extern keyword. This means the code is just a declaration that the actual maps are defined elsewhere in the program (in an external file).
Of course your definitions are in ConsoleApplication1.cpp.
Now you can change your line #include "ConsoleApplication1.cpp" to #include "ConsoleApplication1.h" and that should solve your structural issue.

Initializing vector inside constructor giving seg fault

I have a card class in which I initialize a vector:
#ifndef CARD_H
#define CARD_H
#include <vector>
using namespace std;
class Card
{
private:
vector<int> CC;
vector<int> iChance;
public:
Card();
void draw_Card();
};
#endif
And in my .cpp file I have
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <algorithm>
#include <iterator>
#include "card.h"
using namespace std;
Card::Card()
{
srand(time(NULL));
vector<bool> drawn(20);
for (int i = 0; i < 20; i++)
{
int numvalue = rand()%20 + 1;
if (drawn[numvalue - 1])
{
i--;
continue;
}
else
{
drawn[numvalue - 1] = true;
CC.push_back(numvalue);
iChance.push_back(numvalue);
}
}
copy (CC.begin(), CC.end(), ostream_iterator<int>(cout, " "));
}
It is segfaulting when I call the push_back function for CC, which means the vector CC is not being passed in correctly?
If i called the vectors not in the private area and directly inside the constructor it works. Sorry if this maybe a really simple fix, just started learning classes and vectors. Thank you for the help.
Edit: I am almost certain this is the problem. The value of CC and iChance are not getting past into the constructor, so when the program tries to set a value to the variables nothing exists and it seg faults.
Also I noticed that if i instead declared the CC and iChance variable in the cpp file and not the .h file the program would work.
I am just trying to figure out why and how I could fix this

Why is my array undefined in main when the class headers are included?

So here is the main where i'm trying to call the array by a pointer:
#include <iostream>
#include "Lottery.h"
#include "Player.h"
#include "LotteryData.h"
using namespace std;
int main()
{
Player player;
Lottery random;
LotteryData data;
player.Input();
random.setRandomNumber();
data.PassInfo(int (&Numbers)[6][6]);
}
Apparently "Numbers" is undefined even though the header is included, here's the header and .cpp files relating to it.
LotteryData.h
#pragma once
#include <iostream>
#include <fstream>
#include "Lottery.h"
#include "Player.h"
using namespace std;
class LotteryData
{
private:
public:
LotteryData();
~LotteryData();
void PassInfo(int (&Numbers)[6][6]);
};
LotteryData.cpp
#include <iostream>
#include <fstream>
#include "LotteryData.h"
using namespace std;
LotteryData::LotteryData()
{
}
LotteryData::~LotteryData()
{
}
void LotteryData::PassInfo(int (&Numbers)[6][6])
{
int* ptr;
FILE *Numfile;
Numfile = fopen("C:/Num.txt", "wb");
ptr = &Numbers[6][6];
for (int i=0; i<36; i++)
{
fwrite(ptr, sizeof(int), 36*36, Numfile);
}
fclose(Numfile);
//ofstream out("Numbers.txt");
}
Everything seems fine, I'm puzzled why the reference in the main says the array is undefined, any ideas?
edit: Apologies, missed some bits
Player.h
#pragma once
#include <iostream>
#include <fstream>
using namespace std;
class Player
{
private:
public:
Player();
~Player();
void Input();
int Numbers[6][6];
};
Player.cpp
#include <iostream>
#include <fstream>
#include "Player.h"
using namespace std;
Player::Player()
{
}
Player::~Player()
{
}
void Player::Input()
{
int num(0);
int duplicate = 0;
int game = 0;
int NumberofGames = 0;
cout<<"How many games do you want to play for this weeks draw?"<<endl;
cin>>NumberofGames;
if (NumberofGames>6)
{
cout<<"Please enter an amount between 1 and 6"<<endl;
cin>>NumberofGames;
}
do
{
for (int i=0;i<6;i++)
{
cout<<"Enter Number "<< (i+1) <<endl;
cin>>num;
if (num > 0 && num <67)
{
Numbers[game][i]= num;
}
else
{
cout <<"Please enter number between 1 and 66"<<endl;
i = i-1;
}
}
game = game + 1;
NumberofGames = NumberofGames - 1;
}
while (NumberofGames=0);
}
void PassInfo(int (&Numbers)[6][6]);
That line does not declare an array - it declares a function. You have no declaration for an array in your class (in fact, you have no data members declared in your class at all).
If you want to declare a member array, you need to modify your class definition:
class LotteryData
{
private:
int Numbers[6][6]; // this declares an array
public:
LotteryData();
~LotteryData();
void PassInfo(int (&arr)[6][6]); // this is still a function declaration
};
Just because you made a function's parameter be named Numbers doesn't magically mean that your program has an array called Numbers declared in it.
So a Player has an array called "Numbers".
Then you would use it like this:
data.PassInfo(player.Numbers);
In your main() function,
data.PassInfo(int (&Numbers)[6][6]);
This is wrong. You should simply pass a reference to 2D array.
int (&Numbers)[6][6];
data.PassInfo(Numbers);

syntax error "does not name a type"

Why does my following code produce the following while compiling: error: 'Individual' in class 'Evolve' does not name a type.
#ifndef EVOLVE_H
#define EVOLVE_H
#include <cstdlib>
#include <iostream>
#include <string>
#include "Operator.h"
#include "Individual.h"
using namespace std;
class Evolve
{
public:
Evolve(int length, Operator** operators, int numOperators);
Individual* bestIndividual;
Individual* run(int generations);
Operator operatorArray[];
private:
int length;
int numOperators;
};
#endif
And my class file is
#include <cstdlib>
#include <iostream>
#include <string>
#include "Evolve.h"
#include "Operator.h"
#include "Individual.h"
using namespace std;
Evolve::Evolve(int length, Operator** operators, int numOperators)
{
Individual* bestIndividual = new Individual(length);
}
Evolve::Individual* run(int generations)
{
for(int i=0; i<generations; i++)
{
cout << "test counter = " << i << endl;
}
}
I've read a few other posts about the error and it has all been about what order to declare the function, but I'm not sure if thats the cause of my problem.
The way you implement member function is incorrect.
Update:
Evolve::Individual* run(int generations)
to:
Individual* Evolve::run(int generations)
Also, to initialize member you do not re-define it again.
Evolve::Evolve(int length, Operator** operators, int numOperators)
: bestIndividual(new Individual(length)
{
}
In your constructor,
Individual* bestIndividual = new Individual(length);
you defined a local pointer bestIndividual and it leaks memory.
The general syntax is:
return-type class-name :: function-name(arg list)
Individual* Evolve :: run (int generations)
Fix your Evolve definition