It's crashing at the very end of the main() function where it needs to delete the starters objects. The error message that pops up when I run the program says: Debug assertion failed! Expression: _BLOCK_IS_VALID(pHead->nBlockUse). How do i fix it from crashing when deleting the starters objects?
#include <iostream>
#include <fstream>
#include "olympic.h"
using namespace std;
ofstream csis;
int main() {
const int lanes = 4;
Ranker rank(lanes);
csis.open("csis.txt");
// First make a list of names and lane assignments.
Competitor* starters[lanes];
starters[0] = new Competitor("EmmyLou Harris", 1);
starters[1] = new Competitor("Nanci Griffith", 2);
starters[2] = new Competitor("Bonnie Raitt", 3);
starters[3] = new Competitor("Joni Mitchell", 4);
// The race is run; now assign a time to each person.
starters[0]->setTime((float)12.0);
starters[1]->setTime((float)12.8);
starters[2]->setTime((float)11.0);
starters[3]->setTime((float)10.3);
// Put everyone into the ranker.
for (int i = 0; i < lanes; i++)
rank.addList(starters[i]);
// Now print out the list to make sure its right.
cout << "Competitors by lane are:" << endl;
csis << "Competitors by lane are:" << endl;
for (int i = 1; i <= lanes; i++)
rank.getLane(i)->print();
// Finally, show how they finished.
cout << "Rankings by finish are:" << endl;
csis << "Rankings by finish are:" << endl;
for (int i = 1; i <= lanes; i++)
rank.getFinish(i)->print();
for (int i = 0; i < lanes; i++)
delete starters[i];
csis.close();
}
ranker.cpp:
#include "ranker.h"
#include "competitor.h"
#include <stdlib.h>
Ranker::Ranker(int lanes) {
athlete = new Competitor*[lanes];
numAthletes = 0;
maxAthletes = lanes;
}
int Ranker::addList(Competitor* starter) {
if (numAthletes < maxAthletes && starter != NULL) {
athlete[numAthletes] = starter;
numAthletes++;
return numAthletes;
}
else
return 0;
}
Competitor* Ranker::getLane(int lane) {
for (int i = 0; i < numAthletes; i++) {
if (athlete[i]->getLane() == lane) {
return athlete[i];
}
}
return NULL;
}
Competitor* Ranker::getFinish(int position) {
switch(position) {
case 1:
return athlete[3];
break;
case 2:
return athlete[2];
break;
case 3:
return athlete[1];
break;
case 4:
return athlete[0];
break;
}
return NULL;
}
int Ranker::getFilled() {
return numAthletes;
}
Ranker::~Ranker() {
delete [] athlete;
}
competitor.h:
#ifndef _COMPETITOR_H
#define _COMPETITOR_H
class Competitor {
private:
char* name;
int lane;
double time;
public:
Competitor(char* inputName, int inputLane);
Competitor();
void setTime(double inputTime);
char* getName();
int Competitor::getLane();
double getTime();
void print();
~Competitor();
};
#endif
competitor.cpp:
#include "competitor.h"
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
Competitor::Competitor(char* inputName, int inputLane) {
name = inputName;
lane = inputLane;
}
Competitor::Competitor() {
name = 0;
lane = 0;
time = 0;
}
void Competitor::setTime(double inputTime) {
time = inputTime;
}
char* Competitor::getName() {
return name;
}
int Competitor::getLane() {
return lane;
}
double Competitor::getTime() {
return time;
}
void Competitor::print() {
cout << setw(20) << name << setw(20) << lane << setw(20) << setprecision(4) << time << endl;
}
Competitor::~Competitor() {
delete [] name;
}
Call stack:
before crash: http://i.imgur.com/d4sKbKV.png
after crash: http://i.imgur.com/C5cXth9.png
After you've added Competitor class, it seems the problem is that you delete its name in Competitor's destructor. But you assign it from string literal which can't really be deleted. I'm sure the stack trace leading to assertion will prove that.
One way of solving the problem would be using std::string to store the name.
Problem is when deleting the char* value on destructor, which is assigned with const char instead new char. So i have slightly changed the constructor to copy the const char to new char.
Competitor::Competitor(char* inputName, int charlen, int inputLane)
{
name = new char[charlen + 1];
memcpy(name , inputName, charlen );
name [charlen] = '\0';
lane = inputLane;
}
Related
I working on a program that simulates travel agents booking flights in parallel. It spins up a process for each agent and works against an array of Plane objects held in shared memory.
I'm getting a segmentation fault when I try to push a row of seats back to the plane. The method to parse the input file calls a SetSeats() method on Plane objects. Each Plane contains a vector<map<char, Seat>> (each index of the vector is a row, each key of each map is the letter of a seat on that row). When I call SetSeats() it goes fine through adding seats to the first map, i.e. the first row of seats. It throws the segfault when I try to push the map back to the seats vector.
I saw something online about pushing back custom classes to vectors needing deconstructors, so I added them to Seat.h and Plane.h.
Code for the main program:
#include <iostream>
#include <map>
#include <vector>
#incluce <string>
#include <fstream>
#include "Seat.h"
#include "Plane.h"
void ParseInputFile(ifstream &inFS, int numPlanes, int &numAgents);
int shmid;
int *timer;
int numPlanes, numAgents;
struct sembuf *ops;
Plane *sharedPlanes;
map<string, Plane*> planes;
using namespace std;
int main(int argc, char *argv[])
{
ifstream inFS;
// code to get an input file from command line arguments and get number of planes from it
// set up shared memory segment
long key = XXX; // just a long integer
int nbytes = 1024;
shmid = shmget((key_t)key, nbytes, 0666 | IPC_CREAT);
if (shmid == -1)
{
printf("Error in shared memory region setup.\n");
perror("REASON");
exit(2);
}
// initialize global variables
sharedPlanes = new Plane[numPlanes];
timer = new int;
ops = new sembuf[1];
// attached shared pointers to shared memory segment
sharedPlanes = (Plane*)shmat(shmid, (Plane*)0, 0);
timer = (int*)shmat(shmid, (int*)0, 0);
*timer = 0;
inFS.open(inputFile);
ParseInputFile(inFS, numPlanes, numAgents); // breaks in here
// the rest of main()
}
void ParseInputFile(ifstream &inFS, int numPlanes, int &numAgents)
{
string line = "";
bool foundNumberOfPlanes = false;
bool foundPlanes = false;
bool foundNumberOfAgents = false;
bool lookingForAgent = false;
bool foundAgent = false;
int planeNo = 0;
int agentNo = 0;
int opNo = 0;
map<string, Operation> ops;
vector<Request> agentRequests;
while (getline(inFS, line))
{
if (!CommonMethods::IsWhitespace(line))
{
// code to read first line
if (foundNumberOfPlanes && !foundPlanes)
{
// parse a line from the input file to get details about the plane
Plane *plane = &sharedPlanes[planeNo];
unsigned int rows = xxx; // set based on the plane details
unsigned int seatsPerRow = xxx; set based on the plane details
plane->SetSeats(rows, seatsPerRow); // this is the method where I get the seg fault
// finish defining the plane
continue;
// the rest of the method
}
}
}
}
Code for Plane.h:
#pragma once
#include <iostream>
#include <string>
#include <map>
#include <tuple>
#include <vector>
#include "Seat.h"
#include "Exceptions.h"
#include "ReservationStatus.h"
#include "CommonMethods.h"
using namespace std;
class Plane
{
private:
vector<map<char, Seat>> seats;
unsigned int numberOfRows, numberOfSeatsPerRow;
public:
Plane(unsigned int numberOfRows, unsigned int numberOfSeatsPerRow);
Plane() {}
void SetSeats(unsigned int numberOfRows, unsigned int numberOfSeatsPerRow);
};
void Plane::SetSeats(unsigned int numberOfRows, unsigned int numberOfSeatsPerRow)
{
//cout << "Clearing old seats" << endl;
if (!seats.empty())
{
//cout << "Seats not empty" << endl;
for (int i = 0; i < (int)seats.size(); i++)
{
//cout << "checking row " << i << endl;
if (!seats.at(i).empty())
{
//cout << "Row " << i << " not empty" << endl;
seats.at(i).clear();
}
}
}
cout << "Rows: " << numberOfRows << ", Seats: " << numberOfSeatsPerRow << endl;
this->numberOfRows = numberOfRows;
this->numberOfSeatsPerRow = numberOfSeatsPerRow;
for (unsigned int i = 0; i < this->numberOfRows; i++)
{
map<char, Seat> row;
for (unsigned int j = 0; j < this->numberOfSeatsPerRow; j++)
{
Seat seat;
seat.RowNumber = i + 1;
seat.SeatLetter = j + 'A';
//cout << "Inserting seat " << seat.RowNumber << seat.SeatLetter << endl;
row.insert(pair<char, Seat>(seat.SeatLetter, seat));
}
if (!row.empty())
{
cout << "inserting row " << (i + 1) << endl;
seats.push_back(row);
}
}
}
void Plane::ProcessWaitAny(int t)
{
while (!WaitingList.empty())
{
bool booked = false;
string pass = WaitingList.front();
WaitingList.pop();
for (unsigned int j = 0; j < numberOfRows; j++)
{
if (booked)
break;
for (unsigned int k = 0; k < numberOfSeatsPerRow; k++)
{
Seat *s = &seats.at(j)[k + 'A'];
if (!s->IsBooked)
{
Reserve(s, pass);
booked = true;
string seatNo = to_string(j);
seatNo += (k + 'A');
cout << "Passenger " << pass << " booked into seat " << seatNo << " at time " << t << endl;
break;
}
}
}
if (!booked)
return;
}
}
Code for Seat.h
#pragma once
#include <iostream>
#include <string>
#include <queue>
using namespace std;
struct Seat
{
string Passenger = "";
bool IsBooked = false;
unsigned int RowNumber;
char SeatLetter;
queue<string> WaitingList;
};
I have made a minimum working example of your problem:
#include <vector>
#include <sys/shm.h>
#include <iostream>
class Bar {
public:
Bar() {};
std::vector<int> vec;
};
int main() {
int shmid;
Bar* a = new Bar();
a->vec.push_back(1);
// set up shared memory segment
long key = 0x123455; // just a long integer
int nbytes = 1024;
shmid = shmget((key_t)key, nbytes, 0666 | IPC_CREAT);
if (shmid == -1)
{
printf("Error in shared memory region setup.\n");
perror("REASON");
exit(2);
}
a = (Bar*)shmat(shmid, (Bar*)0, 0);
a->vec.push_back(2);
}
The problem is your wrong usage of shmat. The pointer sharedPlane just points to some unitialized shared memory. You have to make sure that the address provided by key is 'right'. To do this, do the following:
Your other process, call Plane * other_process_sharedPlane = new Plane();. Remove the line sharedPlanes = new Plane[numPlanes]; from your main programm.
In your main process, set key to the value of other_process_sharedPlane
Then you can call shmget and shmadd
I'm trying to find what is the difference between the static and the dynamic allocation of the table in this code, I'm interested most about the initial state or values n that table.
when I tried the code with the static allocation the program didn't work and i can see that the table contain random value but with the dynamic allocation it works better.
can someone explain to me how this work thanks.
#include <string>
#include <stdio.h>
#include <iostream>
using namespace std ;
bool isUnique(std::string s)
{
if(s.length()> 128 ) return false;
//bool lettre[128];
bool* lettre = new bool[128];
for (int i = 0; i < s.length(); i++)
{
int index = s[i];
if (lettre[index] == true)
return false;
lettre[index] = true;
}
for(int i=0; i<128;i++)
{
cout<< lettre[i] +" |";
}
cout<<endl;
return true;
}
int main()
{
std::string s1 = "adcadef";
std::string s2 = "abcdef";
cout<< isUnique(s1) << endl;
cout << isUnique(s2) << endl;
return 0;
}
I'm trying to concatenate two arrays and at the end concatenate int, for example: result = arg + arg + 2;
I'm getting "read access violation" at + operator overloading.
I wrote the error and warning in comments below.
My code:
Main:
#include <iostream>
#include <string>
#include "CTable.h"
int main() {
CTable c_tab1, c_tab0;
c_tab0.SetNewSize(3);
c_tab1.SetNewSize(2);
c_tab0.SetValueAt(0, 22);
c_tab0.SetValueAt(1, 23);
c_tab0.SetValueAt(2, 24);
c_tab0.Print();
c_tab1.SetValueAt(0, 31);
c_tab1.SetValueAt(1, 32);
c_tab1.Print();
CTable c_tab3 = (c_tab0 + c_tab1 + 111);
c_tab3.Print();
return 0;
}
Class CTable:
#include <iostream>
#include <string>
using namespace std;
class CTable {
public:
CTable();
CTable(string sName, int iTableLen);
CTable(const CTable& pcOther);
CTable* pcClone();
~CTable();
void ShowName();
void ShowSize();
void SetName(string sName);
bool SetNewSize(int iTableLen);
void SetValueAt(int iOffset, int iNewVal);
void Print();
CTable& operator+(const CTable& pcNewTable);
CTable operator+(int iNewVal) const;
CTable& operator=(const CTable& pcNewVal) {
if (this != &pcNewVal) {
for (int i = 0; i < i_size; i++) {
this->piTable[i] = pcNewVal.piTable[i];
}
}
return *this;
}
private:
string s_name;
int i_size;
int* piTable;
const int SIZE = 10;
const string NAME = "Name";
};
#include <iostream>
#include <string>
#include "CTable.h"
#include <algorithm>
using namespace std;
CTable::CTable() {
s_name = NAME;
cout << "bezp: " << s_name << endl;
piTable = new int[SIZE];
i_size = SIZE;
}
CTable::CTable(string sName, int iTableLen) {
s_name = sName;
cout << "parametr: " << sName << endl;
piTable = new int[iTableLen];
i_size = iTableLen;
}
CTable::CTable(const CTable& pcOther) {
s_name = pcOther.s_name + "copied";
piTable = new int[pcOther.i_size];
i_size = pcOther.i_size;
for (int i = 0; i < pcOther.i_size; i++) {
piTable[i] = pcOther.piTable[i];
}
}
CTable::~CTable() {
delete[] piTable;
}
void CTable::SetName(string sName) {
s_name = sName;
}
bool CTable::SetNewSize(int iTableLen) {
if (iTableLen <= 0) {
cout << "Length has to be greater than 0" << endl;
return false;
}
int* pi_newTable = new int[iTableLen];
for (int i = 0; i < iTableLen; i++) {
pi_newTable[i] = piTable[i];
}
delete this->piTable;
this->i_size = iTableLen;
this->piTable = pi_newTable;
return true;
}
CTable* CTable::pcClone() {
CTable* ct = new CTable(s_name, i_size);
return ct;
}
void CTable::ShowName() {
cout << "Name: " << s_name << endl;
}
void CTable::ShowSize() {
cout << "Size: " << i_size << endl;
}
void CTable::SetValueAt(int iOffset, int iNewVal) {
if (iOffset >= this->i_size) {
return;
}
piTable[iOffset] = iNewVal;
}
void CTable::Print() {
for (int i = 0; i < i_size; i++) {
cout << piTable[i] << " ";
}
cout << endl;
}
CTable& CTable::operator+(const CTable& pcNewTable) {
CTable result("new_int", this->i_size);
result.i_size = (i_size + pcNewTable.i_size);
result.piTable = new int[i_size + pcNewTable.i_size];
for (int i = 0; i < i_size; i++) {
result.piTable[i] = piTable[i];
}
for (int i = 0; i < (pcNewTable.i_size); i++) {
result.piTable[i+i_size] = pcNewTable.piTable[i];
}
return result; //Warning C4172 returning address of local variable or temporary: result
}
CTable CTable::operator+(int iNewVal) const {
CTable result("new_int", this->i_size);
result.i_size = (i_size + 1);
result.piTable = new int[i_size + 1];
for (int i = 0; i < i_size; i++) {
result.piTable[i] = piTable[i]; //Exception thrown: read access violation. **this->piTable** was 0x1110122.
}
result.piTable[i_size + 1] = iNewVal;
return result;
}
What should I correct? I'm not sure about assigment operator overload, is it okay?
The member function SetNewSize has undefined behavior. In this loop
int* pi_newTable = new int[iTableLen];
for (int i = 0; i < iTableLen; i++) {
pi_newTable[i] = piTable[i];
}
it 1) uses uninitialized values because the array was not initialized and 2) iTableLen can be gretaer than the current value of i_size. You should at least zero initialize the array in constructors.
The copy assignment operator aslo has undefined behabior because the number of elements of the array of the object pcNewVal can be less than the number of elements of the array in the assigned object.
The first overloaded operator + also have undefined behavior. For starters as the warning says the operator returns reference to the local object result that will not be alive after exiting the operator. Secondly, there is a memory leak necause the array of the object is allocated anew and the previuous allocated memory in the constructor is not freed.
CTable result("new_int", this->i_size);
result.i_size = (i_size + pcNewTable.i_size);
result.piTable = new int[i_size + pcNewTable.i_size];
//...
The second overloaded operator + also has undefined behavior. As in the previous operator there is a memory leak.
In this statement
result.piTable[i_size + 1] = iNewVal;
there is an access memory outside the allocated array. There should be
result.piTable[i_size] = iNewVal;
Honestly, I have no idea why CTable cannot convert to CTable? I'm trying to make overload operator + which returns concatenated two tables.
Error C2440 'initializing': cannot convert from 'CTable' to 'CTable'
Second error: Error (active) E0334 class "CTable" has no suitable copy constructor
#include <iostream>
#include <string>
#include "CTable.h"
int main() {
CTable c_tab_1, c_tab_0;
c_tab_0.vSetValueAt(0, 1);
c_tab_0.vPrint();
c_tab_0.bSetNewSize(4);
c_tab_0.vPrint();
c_tab_1.bSetNewSize(4);
c_tab_0.vSetValueAt(0, 1);
c_tab_0.vSetValueAt(1, 2);
c_tab_0.vSetValueAt(2, 3);
c_tab_0.vSetValueAt(3, 4);
c_tab_0.vPrint();
c_tab_1.vSetValueAt(0, 2);
c_tab_1.vSetValueAt(1, 3);
c_tab_1.vSetValueAt(2, 4);
c_tab_1.vSetValueAt(3, 5);
c_tab_1.vPrint();
c_tab_1.vSetValueAt(2, 123);
c_tab_0.vPrint();
c_tab_1.vPrint();
CTable c_tab_3 = c_tab_0 + c_tab_1; //Error C2440! <-----------------------
c_tab_3.vPrint();
return 0;
}
#include <iostream>
#include <string>
using namespace std;
class CTable {
public:
CTable();
CTable(CTable& pcOther);
CTable* pcClone();
~CTable();
bool bSetNewSize(int iTableLen);
void vSetValueAt(int iOffset, int iNewVal);
void vPrint();
CTable operator+(const CTable& pcNewTable);
private:
string s_name;
int i_size;
int* piTable;
const int SIZE = 10;
const string NAME = "Name";
};
#include <iostream>
#include <string>
#include "CTable.h"
using namespace std;
CTable::CTable() {
s_name = NAME;
cout << "bezp: " << s_name << endl;
piTable = new int[SIZE];
i_size = SIZE;
}
///
CTable::CTable(CTable& pcOther) {
s_name = pcOther.s_name + "_copy";
piTable = new int[pcOther.i_size];
i_size = pcOther.i_size;
for (int i = 0; i < pcOther.i_size; i++) {
piTable[i] = pcOther.piTable[i];
}
cout << "kopiuj: " << s_name << endl;
}
CTable::~CTable() {
delete[] piTable;
cout << "usuwam " << s_name << endl;
}
////
bool CTable::bSetNewSize(int iTableLen) {
if (iTableLen <= 0) {
return false;
}
int* pi_newTable = new int[iTableLen];
memcpy(pi_newTable, piTable, iTableLen);
delete this->piTable;
this->i_size = iTableLen;
this->piTable = pi_newTable;
return true;
}
///
void CTable::vSetValueAt(int iOffset, int iNewVal) {
if (iOffset >= this->i_size) {
return;
}
piTable[iOffset] = iNewVal;
}
void CTable::vPrint() {
for (int i = 0; i < i_size; i++) {
cout << piTable[i] << " ";
}
cout << endl;
}
CTable CTable::operator+(const CTable& pcNewTable) {
CTable result;
int greater_len = i_size < pcNewTable.i_size;
int smaller_len = i_size > pcNewTable.i_size;
int* greater_table = i_size > pcNewTable.i_size ? piTable : pcNewTable.piTable;
int* smaller_table = i_size <= pcNewTable.i_size ? piTable : pcNewTable.piTable;
result.i_size = greater_len;
result.piTable = new int[greater_len];
memcpy(result.piTable, greater_table, greater_len * sizeof(int));
for (int i = 0; i < smaller_len; i++) {
result.piTable[i] += smaller_table[i];
}
return result;
}
What should I correct?
Try to define
CTable(const CTable& pcOther)
{
.......
}
My program is to print the queue of information from a file but i have problem with my following code. When i run the program it keep loop. I cant figure out the problem. Any help?
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <queue>
#include <list>
using namespace std;
void simulation(ifstream &infile);
void processArrival(int *newEvent, ifstream &inFile, list<int> eventList,queue<int> printQueue);
void processDeparture(int *newEvent, list<int> eventList,queue<int> printQueue);
string name[100];
int timeAccepted[100];
int fileSize[100];
int i = 1;
int j = 1;
int currentTime;
bool checker = true;
int main(void)
{
ifstream inFile;
string fileName;
int i = 0;
inFile.open("123.txt", ios::in);
simulation(inFile);
/*while(inFile.peek() != EOF )
{
inFile>>name[i]>>timeAccepted[i]>>fileSize[i];
i++;
}
for(int s = 0; s < i; s++)
{
cout << name[s] << timeAccepted[s] << fileSize[s] <<endl;
}*/
return 0;
}
void simulation(ifstream &inFile)
{
queue<int> printQueue;
list<int> eventList;
int *newEvent;
while(inFile.peek() != '\n')
{
inFile>>name[0]>>timeAccepted[0]>>fileSize[0];
}
eventList.push_front(timeAccepted[0]);
int checkEmpty = eventList.empty();
newEvent = &eventList.front();
while(checkEmpty ==0)
{
newEvent = &eventList.front();
if(checker)
{
processArrival(newEvent, inFile, eventList, printQueue);
}
else
{
processDeparture(newEvent, eventList, printQueue);
}
checkEmpty = eventList.empty();
}
}
void processArrival(int *newEvent, ifstream &inFile, list<int> eventList,queue<int> printQueue)
{
int atFront=0;
atFront = printQueue.empty();
cout << atFront <<endl;
printQueue.push(*newEvent);
cout << printQueue.front() <<endl;
eventList.remove(*newEvent);
int temp;
if(atFront==1)
{
currentTime = *newEvent + fileSize[0];
cout << name[0] << " ## " << *newEvent << " ## " << currentTime << endl;
eventList.push_back(currentTime);
}
checker = false;
if(inFile.peek() != EOF )
{
inFile>>name[i]>>timeAccepted[i]>>fileSize[i];
eventList.push_back( timeAccepted[i] );
i++;
checker = false;
if(eventList.back() <= eventList.front())
{
temp = eventList.back();
eventList.back() = eventList.front();
eventList.front() = temp;
checker = true;
}
}
}
void processDeparture(int *newEvent, list<int> eventList,queue<int> printQueue)
{
printQueue.pop();
eventList.pop_front();
int checkEmpty = 1;
checkEmpty = printQueue.empty();
int temp;
if(checkEmpty ==0)
{
currentTime = *newEvent + fileSize[j];
cout << name[j] << " " << *newEvent << " " << currentTime << endl;
eventList.push_back(currentTime);
checker = true;
if(eventList.back() < eventList.front())
{
temp = eventList.back();
eventList.back() = eventList.front();
eventList.front() = temp;
checker = false;
}
j++;
}
}
Your processArrival and processDeparture functions are taking their eventList and printQueue arguments by value. This means that when you call them, for example in this line:
processArrival(newEvent, inFile, eventList, printQueue);
Copies of eventList and printQueue are made and passed into the processArrival function. The processArrival function then operates on those copies, and the original data is never modified. In particular, this means that the original eventList will never have any items removed from it, so it will never be empty -- it will just keep trying to process the first event over and over again.
The solution is to pass these parameters by reference. i.e. change the definition of processArrival to
void processArrival(int *newEvent, ifstream &inFile, list<int>& eventList, queue<int>& printQueue)
Note the & characters that I have inserted before eventList and printQueue. These cause references to the original data, rather than copies of the original data, to be passed into the processArival function. This means that processArrival will operate directly on the original data as you intend it to. Don't forget to make the corresponding change to processDeparture as well.