When I execute this code in Code::Blocks I get a segmentation fault. Why? I've used debug and haven't found why. Any help is useful.
The debugger showed it was from the vector push_back method, but specifically on the "this" pointer used in the copy constructor.
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <cmath>
const int MAX_COL = 7, MAX_ROW = 6;
const int NOPLAYER = 0, PLAYER1 = 1, PLAYER2 = 2;
const int NOTHING = 123;
int movesBeingStored = 0;
int movesCreated = 0;
class Move{
public:
Move() : row(-1), col(-1), plr(-1) {
//std::cout << "Placed #" << col << "," << row << std::endl;
++movesBeingStored;
++movesCreated;
std::cout << "+Now " << movesBeingStored << " move(s), Created " << movesCreated << std::endl;
};
Move(int r, int c, int p) : row(r), col(c), plr(p) {
++movesBeingStored;
++movesCreated;
std::cout << "+Now " << movesBeingStored << " move(s), Created " << movesCreated << std::endl;
};
~Move() {
--movesBeingStored;
std::cout << "-Now " << movesBeingStored << " move(s)" << std::endl;
};
int getRow() const { return row; }
int getCol() const { return col; }
int getPlayer() const { return plr; }
Move(const Move* other) {
++movesBeingStored;
++movesCreated;
std::cout << "+Now " << movesBeingStored << " move(s), Created " << movesCreated << std::endl;
col = other->getCol();
row = other->getRow();
plr = other->getPlayer();
}
Move(const Move& other) {
++movesBeingStored;
++movesCreated;
std::cout << "+Now " << movesBeingStored << " move(s), Created " << movesCreated << std::endl;
col = other.getCol(); //This line causes a segment fault
row = other.getRow();
plr = other.getPlayer();
}
bool operator== (const Move& other) const {
return (&other == this);
}
private:
int row, col, plr;
};
int board[MAX_COL * MAX_ROW];
std::vector<Move> moves;
bool isFull[MAX_COL];
int tops[MAX_COL];
int currentPlayer = PLAYER1;
int checkedCollumns = 0;
void randomize( void ) { srand(time(NULL)); }
void startBoard( void );
void placeMove(int col, int player);
void popMove();
int checkwin(int curPlayer);
int checkMove(int depth, int& bestCol, int curP, int checkP);
int randomInt(int min, int max);
void printMoves( void );
int main()
{
startBoard();
randomize();
int col = -1;
int pts = checkMove(2, col, PLAYER1, PLAYER1);
if(col == -1) {
std::cout << "No best move" << std::endl;
} else {
std::cout << "Best move: Col " << col << std::endl;
if(pts == NOTHING) {
std::cout << "Nothing happens" << std::endl;
} else {
std::cout << "Gives " << pts << " points" << std::endl;
}
}
}
void startBoard( void ) {
for(int i = 0; i < MAX_COL; ++i) {
isFull[i] = false;
tops[i] = 0;
}
for(int p = 0; p < MAX_COL * MAX_ROW; ++p) {
board[p] = NOPLAYER;
}
}
void placeMove(int col, int player) {
if(col < 0 || col >= MAX_COL)
return;
if(isFull[col])
return;
if(player != PLAYER1 && player != PLAYER2)
player = PLAYER1;
moves.push_back(Move(col, tops[col], player));
board[col + tops[col] * MAX_COL] = player;
++tops[col];
isFull[col] = (tops[col] == MAX_ROW);
}
void popMove() {
if(moves.empty())
return;
Move move = moves.back();
moves.pop_back();
int col = move.getCol(), row = move.getRow();
board[col + row * MAX_COL] = NOPLAYER;
tops[col] = row;
isFull[col] = (tops[col] == MAX_ROW);
}
int checkwin(int curPlayer) {
if(randomInt(0,5) != 1)
return NOTHING;
return randomInt(0,4);
}
int checkMove(int depth, int& bestCol, int curP, int checkP) {
int pts = NOTHING, col = -1, p = NOTHING, c = -1;
if(depth <= 0) {
if(moves.empty()) {
bestCol = -1;
return NOTHING;
}
Move move = moves.back();
bestCol = move.getCol();
pts = checkwin((move.getPlayer());
if(move.getPlayer() != checkP && pts != NOTHING)
pts = -pts;
return pts;
}
for(int i = 0; i < MAX_COL; ++i) {
std::cout << "C: " << checkedCollumns;
std::cout << "\tD: " << depth;
std::cout << "\tM: " << moves.size();
std::cout << std::endl;
if(isFull[i])
continue;
++checkedCollumns;
placeMove(i, curP);
p = checkMove(depth - 1, c, ((curP == PLAYER1)?PLAYER2:PLAYER1), checkP);
popMove();
if(p != NOTHING && checkP != curP)
p = -p;
if(col == -1) {
col = i;
pts = p;
continue;
}
if(pts == NOTHING && p != NOTHING && p >= 0) {
col = i;
pts = p;
continue;
}
if(pts != NOTHING && p != NOTHING && p > pts) {
col = i;
pts = p;
}
}
bestCol = col;
return pts;
}
int randomInt(int min, int max) {
double per = (double)(rand() % RAND_MAX) / RAND_MAX;
return min + (max - min) * per;
}
void printMoves( void ) {
std::cout << "M:";
if(moves.empty()) {
std::cout << " --\t" << moves.size();
return;
}
Move m;
for(unsigned int i = 0; i < moves.size(); ++i) {
m = moves.at(i);
std::cout << " {" << m.getCol() << "," << m.getRow() << "}";
}
std::cout << "\t" << moves.size();
}
A very trivial error, manifesting in a very obscure way. The segment fault is caused by the vector trying to construct an object at an invalid location. Why? Because of the following line in void popMove():
board[col + row * MAX_COL] = NOPLAYER;
This line has a buffer overflow caused by invalid coordinates (0, 6), which overwrites the internal memory pointer in moves. That's the problem, the solution is up to you.
Related
Code given below is not executed completely;
I have looked for everything on web but I don't know why it is working for starting numbers from nums (i.e. 1000 and sometimes 5000) and after that it starts execution but in between program terminates itself and stopes working.
#include <bits/stdc++.h>
// #include <iostream>
// #include <chrono>
// #include <vector>
#define UPPER_LIMIT 10
using namespace std;
using namespace std::chrono;
bool inTimeLimit = true;
bool isFinished = false;
bool isRunning = true;
class Timer {
public:
time_point<high_resolution_clock> start, end;
Timer() {
start = high_resolution_clock::now();
}
~Timer() {
end = high_resolution_clock::now();
auto durationTime = durationCounter();
cout << "\n\nTaken time Duration " << (unsigned long long)durationTime << " us; " << (unsigned long long)durationTime * 0.001 << "ms.";
}
float durationCounter() {
auto currTime = high_resolution_clock::now();
auto durationTime = duration_cast<microseconds>(currTime - start);
return durationTime.count();
}
};
void printVector(vector <int> v) {
cout << endl;
for (int x : v) {
cout << setw(3) << x << " ";
}
}
void printVectorToFile(ofstream &fout , vector <int> v, string msg) {
fout << "\n\n===================\n\n";
fout << msg << endl;
fout << endl;
for (int x : v) {
fout << setw(5) << x << " ";
}
fout << endl;
}
void swap (int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
vector <int> randomArrayGenerator(int n) {
vector<int> v(n);
for (int i = 0; i < n; ++i)
v[i] = i + 1;
srand(time(0));
for (int i = 0; i < n; ++i)
{
int pos = rand() % n;
swap(&v[i], &v[pos]);
}
return v;
}
string sortingChecker(vector<int> v) {
for (int i = 0; i < (int)v.size() - 1; ++i)
{
if (v[i] > v[i + 1]) return "false";
}
return "true";
}
bool sortChecker(vector<int> v) {
for (int i = 0; i < (int)v.size() - 1; ++i)
{
if (v[i] > v[i + 1]) return false;
}
return true;
}
// Merge function
void merge(vector <int> &v, int begin, int middle, int end) {
vector <int> left, right;
for (int i = begin; i < middle + 1; ++i)
{
left.push_back(v[i]);
}
for (int i = middle + 1; i <= end; ++i)
{
right.push_back(v[i]);
}
int p1 = 0, p2 = 0, n1 = left.size(), n2 = right.size(), p = begin;
while ((p1 < n1 ) || (p2 < n2)) {
if ((p1 != n1 ) && ((p2 == n2) || left[p1] < right[p2]))
v[p++] = left[p1++];
else
v[p++] = right[p2++];
}
}
void mergeSortByIteration(vector <int> &v, bool &isTimeDelayed) {
int low = 0, high = v.size();
cout << "Thread ID: " << this_thread::get_id() << endl;
// n :for taking individual block of vector containing number of elements n=[1,2,4,8,..]
for (int n = 1; n < high; n *= 2) {
if (isTimeDelayed) return;
// taking block according to n and then sorting them by merge function
// n=1 => i=0,2,4,8,16
// n=2 => i=0,4,8
for (int i = 0; i < high; i += 2 * n) {
if (isTimeDelayed) return;
int begin = i;
int mid = i + n - 1;
int end = min(i + 2 * n - 1 , high - 1);
merge(v, begin, mid, end);
}
}
}
// Merge by recurision
void mergeSortByRecursion (vector <int> &v, int begin, int end, bool &isTimeDelayed) {
if (end <= begin || isTimeDelayed) return;
int middle = begin + (end - begin) / 2;
mergeSortByRecursion(v, begin, middle, isTimeDelayed);
mergeSortByRecursion(v, middle + 1, end, isTimeDelayed);
merge(v, begin, middle, end);
}
int main() {
int nums[] = {1000, 5000, 10000, 50000, 100000};
// int nums[] = {50000};
ofstream vectorOutput ;
vectorOutput.open("outputTexts\\prac1_resultedArrays.txt", ios::trunc);;
for (int n : nums)
// ``````` Merge by Iteration ````````
{
vector<int> num, arr = randomArrayGenerator(n);
cout << "\n=======";
cout << "\n\nMerge by Iteration:" << endl;
num = arr;
cout << "Array size: " << num.size() << endl;
bool isTimeOut = false, isSorted = false;
Timer timer;
std::thread worker(mergeSortByIteration, ref(num), ref(isTimeOut));
// mergeSortByIteration(num, isTimeOut);
// std::thread worker(mergeSortByRecursion, ref(num), 0, n - 1, ref(isTimeOut));
while ( ( ( timer.durationCounter() / 1000000 ) < 5) && (!isSorted ) ) {
// this_thread::sleep_for(seconds(1));
// cout << timer.durationCounter() << " ";
isSorted = sortChecker(num);
}
if ( ( ( ( timer.durationCounter() / 1000000 ) > 5) && (!isSorted ) ) )
{
isTimeOut = true;
cout << endl << "!!!!!Execution Terminated ---- Time Limit reached!!!!!!" << endl;
}
if (worker.joinable())
worker.join();
printVector(num);
cout << "\nCheck result for sorted Vector:" << (isSorted ? "true" : "false") << endl;
// printVectorToFile(vectorOutput, num, "Merge By Iteration for size:" + to_string(n) );
}
cout << "\n\ndone" << endl;
return 0;
}
can anyone help me out here?
If issue is not clear fill free to ask.
This is some code I'm working on for school. When I run it I get a bad_alloc error. It's most likely somewhere in the class definitions, but nothing i tried works. Can someone tell me where the bad allocation is happening?
#include <iostream>
#include <vector>
using namespace std;
enum Dir
{
LEFT = 1,
RIGHT = 1 << 1,
UP = 1 << 2,
DOWN = 1 << 3,
};
class Cell
{
friend class Board;
int row_, col_;
bool visited_;
unsigned int walls_;
Cell* up_;
Cell* down_;
Cell* left_;
Cell* right_;
Cell& set_up(Cell *up)
{
up_ = up;
return *this;
}
Cell& set_down(Cell *down)
{
down_ = down;
return *this;
}
Cell& set_left(Cell *left)
{
left_ = left;
return *this;
}
Cell& set_right(Cell *right)
{
right_ = right;
return *this;
}
public:
Cell( int row = -1, int col = -1)
:row_(row), col_(col), visited_(false), walls_(LEFT | RIGHT | UP | DOWN){}
bool visited() const
{
return visited_;
}
bool hasWall(Dir d) const
{
return walls_ & d;
}
void drill(Dir d)
{
walls_ &= ~d;
}
void draw(int step = 20) const
{
cout << col_*step << " " << row_*step << " " << "moveto" << endl;
cout << step << " " << 0 << " " << (hasWall(DOWN)?"rlineto":"rmoveto") << endl;
cout << 0 << " " << step << (hasWall(RIGHT)?"rlineto":"rmoveto") << endl;
cout << -step << " " << 0 << " " << (hasWall(UP)?"rlineto":"rmoveto") << endl;
cout << 0 << " " << -step << (hasWall(DOWN)?"rlineto":"rmoveto") << endl;
}
Cell* up() const
{
return up_;
}
Cell* down() const
{
return down_;
}
Cell* left() const
{
return left_;
}
Cell* right() const
{
return right_;
}
};
class Board
{
friend class Cell;
int rows_, cols_;
vector<Cell> cells_;
public:
Board(int rows, int cols)
: rows_(rows), cols_(cols)
{
for(int i = 0; i < rows_; i++)
for (int j = 0; i < cols_; j++)
cells_.push_back(Cell(i, j));
for (int i = 0; i < rows_ ; i++)
for(int j = 0; j < cols_; j++)
{
Cell& c = at(i, j);
if(i < rows_ - 1)
c.set_up(&at(i + 1 , j));
if(i > 0)
c.set_down(&at(i - 1 , j));
if(j > 0)
c.set_left(&at(i , j - 1));
if(j < cols_ - 1)
c.set_right(&at(i, j + 1));
}
}
Cell& at(int i, int j)
{
int index = i*cols_ + j;
return cells_[index];
}
const Cell& at(int i, int j) const
{
int index = i*cols_ + j;
return cells_[index];
}
void draw() const
{
cout << "newpath" << endl;
for (vector<Cell>::const_iterator it = cells_.begin(); it != cells_.end(); ++it)
{
(*it).Cell::draw();
}
cout << "stroke" << endl;
cout << "showpage" << endl;
}
};
int main()
{
Board b(5, 5);
Cell& c = b.at(2, 2);
c.drill(UP);
Cell* up = c.up();
up->drill(DOWN);
b.draw();
return 0;
}
Board constructor - second for() you have wrong termination condition. There should be "j < cols_" instead of "i < cols_".
Non-Recursive Code
Here is the code I am trying to convert into a recursive solution.
int main()
{
int number[3];
for (number[0]=0; number[0] <= 9; number[0]++)
{
for (number[1]=0; number[1] <= 4; number[1]++)
{
for (number[2]=0; number[2] <= 9; number[2]++)
{
std::cout << number[0] << number[1] << number[2] << std::endl;
}
}
}
std::cout << "Press any key to continue";
std::cin.ignore();
return 0;
}
The output of this code can be found here http://pastebin.com/f20X3gT3.
Recursive Attempt
Here is my failed attempt at replicating the above algorithm into a recursive solution. It compiles without any errors but it does not give the same results as the above Non-Recursive solution does.
#include <iostream>
const int NumberLength = 3;
int number[3];
int element;
void generateFormula(const int Length) {
if(Length == 0) {
for (int n = 0; n <= NumberLength; ++n) {
std::cout << number[n];
}
std::cout << std::endl;
return;
}
if(element%2==0) {
for(number[element]=0; number[element] <= 9; number[element]++);
generateFormula(Length-1);
}
else {
for(number[element]=0; number[element] <= 4; number[element]++);
generateFormula(Length-1);
}
element++;
}
int main()
{
for (int i = 0; i <= NumberLength; ++i)
generateFormula(i);
std::cout << "Press any key to continue";
std::cin.ignore();
return 0;
}
Output:
0000
10000
10501
10500
If you change your function a little bit, you'll be able to see how it can be transformed to a recursive function.
// Drive it using externally supplied data.
void generateFormula1(int number[], int loopCounter[])
{
for (; number[0] <= loopCounter[0]; number[0]++)
{
for (; number[1] <= loopCounter[1]; number[1]++)
{
for (; number[2] <= loopCounter[2]; number[2]++)
{
std::cout << number[0] << number[1] << number[2] << std::endl;
}
}
}
}
Now, it is a bit easier to transform it to a recursive function.
void generateFormula2(int number[], int loopCounter[], int nestingLevel)
{
// The terminating condition of the recursive function.
if ( nestingLevel == 3 )
{
std::cout << number[0] << number[1] << number[2] << std::endl;
return;
}
for (; number[nestingLevel] <= loopCounter[nestingLevel]; number[nestingLevel]++)
{
generateFormula2(number, loopCounter, nestingLevel+1);
}
}
Test it using:
int main()
{
int loopCounter[3] = {9, 4, 9};
int number1[3] = {0};
generateFormula1(number1, loopCounter);
int number2[3] = {0};
generateFormula2(number2, loopCounter, 0);
return 0;
}
See it working at http://ideone.com/JH76sa.
You can simplify your function quite a bit. Using std::setw() and std::setfill() you don't need to have three different variables.You can change the iterative approach to
void print()
{
for (int i = 0; i < 950; i++)
{
cout << setw(3) << setfill('0') << i << "\n";
if (((i+1) % 50) == 0)
i += 50;
}
}
Live Example
And the recursive approach would become:
void print(int i)
{
cout << setw(3) << setfill('0') << i << "\n";
if (i == 949)
return;
if (((i+1) % 50) == 0)
i += 50;
print(++i);
}
Live Example
void print(int x, int y, int z){
std::cout << '(' << x << ", " << y << ", " << z << ")\n";
++x;
if(x == 10){
x = 0;
++y;
if(y == 10){
y = 0;
++z;
if(z == 10)
return;
}
}
print(x, y, z);
}
auto main() -> int{
print(0, 0, 0);
}
This will print out (0, 0, 0) through to (9, 9, 9)
You can replace x, y and z with whatever you like and modify the parameters of the if statements to get the results you want. You could also generalize the function to get a limit for each parameter:
template<int XLim, int YLim, int ZLim>
void print(int x, int y, int z){
std::cout << '(' << x << ", " << y << ", " << z << ")\n";
if(z >= ZLim && y >= YLim && z >= ZLim) return;
++x;
if(x == 10){
x = 0;
++y;
if(y == 10){
y = 0;
++z;
if(z == 10) return;
}
}
print<XLim, YLim, ZLim>(x, y, z);
}
auto main() -> int{
print<9, 4, 9>(0, 0, 0);
}
Can someone please help me. I am struggling to find in my code why the last value in column B always gets incremented by one. I have written some code since its an assignment due today. I also cant figure out why the last value in column B is not equal to 196 because in the reset function it sets all the values in the array to 196 . Any suggestion would be appreciated. Thank you in advance
#include <iostream> //includes cin cout
#include <iomanip>
using namespace std; //setting up the environment
const int NUMBER_OF_ROWS = 3;
const int NUMBER_OF_COLUMNS = 3;
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats);
bool isFull(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
bool isEmpty(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
int main() { //main starts
int maxSeats;
int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
int SeatCountNumber = 0;
bool anyFreeSeats;
reset(seats);
anyFreeSeats = true;
SeatCountNumber = 0;
while (anyFreeSeats) {
printAllSeats(seats);
askForUsersSeat(seats, SeatCountNumber, anyFreeSeats);
}
system("pause");
return 0;
} //main ends
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]) {
cout << endl;
cout << setw(10) << " - = Available R = Reserved\n\n";
for (int i = 0; i <= NUMBER_OF_ROWS; i++) {
cout << setw(15) << i << " ";
for (int j = 0; j < NUMBER_OF_COLUMNS; j++) {
if (i == 0) {
cout << " " << static_cast<char>(j + 65) << " ";
} else {
cout << " " << static_cast<char>(seats[i][j]) << " ";
}
}
cout << endl;
}
cout << endl;
}
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]) {
//set all values in array to 196
for (int i = 0; i <= NUMBER_OF_ROWS; i++) {
for (int j = 0; j <= NUMBER_OF_COLUMNS; j++) {
seats[i][j] = 196;
}
}
}
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats) {
int seatChoiceNumber;
char seatChoiceLetter;
int letter;
int maxSeats = NUMBER_OF_ROWS * NUMBER_OF_COLUMNS;
cout << "Seat (Row, Column): ";
cin >> seatChoiceNumber >> seatChoiceLetter;
letter = static_cast<int>(toupper(seatChoiceLetter));
if (((letter >= 65) && (letter < (65 + NUMBER_OF_COLUMNS))) && ((seatChoiceNumber > 0) && (seatChoiceNumber <= NUMBER_OF_ROWS))) {
if (seats[(seatChoiceNumber)][(letter - 65)] == 82) {
} else {
seats[(seatChoiceNumber)][(letter - 65)] = 82;
SeatCountNumber++; //this changes last value in column B for some reason
if (SeatCountNumber < maxSeats) {
anyFreeSeats = true;
}
else if (SeatCountNumber > maxSeats) {
printAllSeats(seats);
anyFreeSeats = false;
}
}
} else {
}
}
I kind of cleaned up the code a bit. It seems you found your answer in the comments, so I just did some indentation. Try and eliminate whitespaces in your code (mind you, the one I am putting here is not perfect either, but you get the point). Clean and easy to read code doesn't only make it better for you, but as you get higher up in the industry and other people begin reading and working on your code, having clean and easy to read code really helps :)
#include <iostream> //includes cin cout
#include <iomanip>
using namespace std; //setting up the environment
const int NUMBER_OF_ROWS = 3;
const int NUMBER_OF_COLUMNS = 3;
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats);
bool isFull(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
bool isEmpty(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
int main()
{
int maxSeats;
int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
int SeatCountNumber = 0;
bool anyFreeSeats;
reset(seats);
anyFreeSeats = true;
SeatCountNumber = 0;
while (anyFreeSeats)
{
printAllSeats(seats);
askForUsersSeat(seats, SeatCountNumber, anyFreeSeats);
}
system("pause");
return 0;
} //main ends
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS])
{
cout << endl;
cout << setw(10) << " - = Available R = Reserved\n\n";
for (int i = 0; i <= NUMBER_OF_ROWS; i++)
{
cout << setw(15) << i << " ";
for (int j = 0; j < NUMBER_OF_COLUMNS; j++)
{
if (i == 0)
{
cout << " " << static_cast<char>(j + 65) << " ";
}
else
{
cout << " " << static_cast<char>(seats[i][j]) << " ";
}
}
cout << endl;
}
cout << endl;
}
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS])
{
//set all values in array to 196
for (int i = 0; i <= NUMBER_OF_ROWS; i++)
{
for (int j = 0; j <= NUMBER_OF_COLUMNS; j++)
{
seats[i][j] = 196;
}
}
}
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats)
{
int seatChoiceNumber;
char seatChoiceLetter;
int letter;
int maxSeats = NUMBER_OF_ROWS * NUMBER_OF_COLUMNS;
cout << "Seat (Row, Column): ";
cin >> seatChoiceNumber >> seatChoiceLetter;
letter = static_cast<int>(toupper(seatChoiceLetter));
if (((letter >= 65) && (letter < (65 + NUMBER_OF_COLUMNS))) && ((seatChoiceNumber > 0) && (seatChoiceNumber <= NUMBER_OF_ROWS)))
{
if (seats[(seatChoiceNumber)][(letter - 65)] == 82)
{
}
else
{
seats[(seatChoiceNumber)][(letter - 65)] = 82;
SeatCountNumber++; //this changes last value in column B for some reason
if (SeatCountNumber < maxSeats)
{
anyFreeSeats = true;
}
else if (SeatCountNumber > maxSeats)
{
printAllSeats(seats);
anyFreeSeats = false;
}
}
}
else {
}
}
Note: Some more whitespaces could even come out but I generally like to have spaces after certain statements (personal preference).
when i put the code below in my solution and then debug it, a massage containing this "Unhandled exception at 0x0016ec86 in Q2.exe: 0xC0000005: Access violation reading location 0x00000000." come up on my screen.
i think it's due to "cout" but i don't know how to solve it
""code is written in "systemC" a library of c++""
#ifndef IF_classes
#define IF_classes
#include "systemc.h"
#include <iostream>
class put_if : virtual public sc_interface
{
public:
virtual void put(sc_lv<8>[16], int) = 0;
};
class get_if : virtual public sc_interface
{
public:
int d;
virtual void get(sc_lv<8>[16], int) = 0;
};
#endif
#include "IF_classes.h"
class router : public put_if, public get_if
{
bool full[4];
sc_lv<8> reg[4];
int rf;
sc_signal<bool> getD_ev[4], putD_ev[4], timeout_ev;
public:
router() {};
~router() {};
void put(sc_lv<8> data[16], int RF);
void get(sc_lv<8> data[16], int d);
};
#include "router.h"
void router::put(sc_lv<8> data[16], int RF)
{
rf = RF;
if (rf < 0) //////////////////////////Routing Field < 0
{
rf = abs(rf+1)%4;
for(int i = 0; i<= 15; i++)
{
if (full[rf] == true)
wait (getD_ev[rf].posedge());
reg[rf] = data[i];
full[rf] = true;
getD_ev[rf] = 0;
putD_ev[rf] = 1;
}
}
else if (rf == 0) ////////////////////Routing Field == 0
{
int i = 0;
while ( i < 16)
{
if (full[0] = false)
for(i = 0; i <= 15; i++)
{
if (full[0] == true)
wait (getD_ev[0].posedge());
reg[0] = data[i];
full[0] = true;
getD_ev[0] = 0;
putD_ev[0] = 1;
}
else if (full[1] = false)
for(i = 0; i <= 15; i++)
{
if (full[1] == true)
wait (getD_ev[1].posedge());
reg[1] = data[i];
full[1] = true;
getD_ev[1] = 0;
putD_ev[1] = 1;
}
else if (full[2] = false)
for(i = 0; i <= 15; i++)
{
if (full[2] == true)
wait (getD_ev[2].posedge());
reg[2] = data[i];
full[2] = true;
getD_ev[2] = 0;
putD_ev[2] = 1;
}
else if (full[3] = false)
for(i = 0; i <= 15; i++)
{
if (full[3] == true)
wait (getD_ev[3].posedge());
reg[3] = data[i];
full[3] = true;
getD_ev[3] = 0;
putD_ev[3] = 1;
}
}
}
else /////////////////////////////////Routing Field > 0
{
for(int j = 0; j < rf; j++)
{
if (full[0] = false)
for(int i = 0; i <= 15; i++)
{
if (full[0] == true)
wait (getD_ev[0].posedge());
reg[0] = data[i];
full[0] = true;
getD_ev[0] = 0;
putD_ev[0] = 1;
}
else if (full[1] = false)
for(int i = 0; i <= 15; i++)
{
if (full[1] == true)
wait (getD_ev[1].posedge());
reg[1] = data[i];
full[1] = true;
getD_ev[1] = 0;
putD_ev[1] = 1;
}
else if (full[2] = false)
for(int i = 0; i <= 15; i++)
{
if (full[2] == true)
wait (getD_ev[2].posedge());
reg[2] = data[i];
full[2] = true;
getD_ev[2] = 0;
putD_ev[2] = 1;
}
else if (full[3] = false)
for(int i = 0; i <= 15; i++)
{
if (full[3] == true)
wait (getD_ev[3].posedge());
reg[3] = data[i];
full[3] = true;
getD_ev[3] = 0;
putD_ev[3] = 1;
}
if (j = rf)
timeout_ev = 1;
}
}
}
void router :: get( sc_lv<8> data[16],int d)
{
for(int i = 0; i <= 15; i++)
{
if (full[d] == false)
wait (putD_ev[d].posedge());
data[i] = reg[d];
full[d] = false;
putD_ev[d] = 0;
getD_ev[d] = 1;
}
}
#ifndef transfer
#define transfer
#include "router.h"
SC_MODULE (source)
{
sc_port<put_if> out;
void putting();
SC_CTOR(source)
{
SC_THREAD(putting);
}
};
SC_MODULE (drain)
{
sc_port<get_if> in1, in2, in3, in4;
void getting();
SC_CTOR(drain)
{
SC_THREAD(getting);
}
};
#endif
#include "transfer.h"
void source :: putting()
{
sc_lv<8> to_put[16];
int routing_field;
for (int i = 0; i < 128 ; i++)
{
wait(2, SC_NS);
to_put[i%16] = (sc_lv<8>) i;
if (i%16 == 0 && i != 0)
{
routing_field = ((-1)^(i))*(rand()%4);
out->put(to_put, routing_field);
cout << "At: " << sc_time_stamp() << "\n" << to_put[0]
<< "\n" << to_put[1]
<< "\n" << to_put[2]
<< "\n" << to_put[3]
<< "\n" << to_put[4]
<< "\n" << to_put[5]
<< "\n" << to_put[6]
<< "\n" << to_put[7]
<< "\n" << to_put[8]
<< "\n" << to_put[9]
<< "\n" << to_put[10]
<< "\n" << to_put[11]
<< "\n" << to_put[12]
<< "\n" << to_put[13]
<< "\n" << to_put[14]
<< "\n" << to_put[15]
<< "\n" << " was transmitted to: rf" << routing_field+1 << ".\n";
}
}
}
void drain :: getting()
{
sc_lv<8> what_got[16];
for (int i = 0; i < 128; i++)
{
wait(2,SC_NS);
in1->get(what_got, 0);
in2->get(what_got, 1);
in3->get(what_got, 2);
in4->get(what_got, 3);
if (i%16 == 0 && i != 0)
{
cout << "At: " << sc_time_stamp() << "\n" << what_got[0]
<< "\n" << what_got[1]
<< "\n" << what_got[2]
<< "\n" << what_got[3]
<< "\n" << what_got[4]
<< "\n" << what_got[5]
<< "\n" << what_got[6]
<< "\n" << what_got[7]
<< "\n" << what_got[8]
<< "\n" << what_got[9]
<< "\n" << what_got[10]
<< "\n" << what_got[11]
<< "\n" << what_got[12]
<< "\n" << what_got[13]
<< "\n" << what_got[14]
<< "\n" << what_got[15]
<< "was recieved at: " << "\n";
}
}
}
#include "transfer.h"
SC_MODULE (transfer_tb)
{
router *rout;
source *S;
drain *D1, *D2, *D3, *D4;
SC_CTOR (transfer_tb)
{
//rout = new router();
S = new source("source");
S->out(*rout);
D1 = new drain("drain1");
D1->in1(*rout);
D2 = new drain("drain2");
D2->in2(*rout);
D3 = new drain("drain3");
D3->in3(*rout);
D4 = new drain("drain4");
D4->in4(*rout);
}
};
#include "transfer_tb.h"
int sc_main (int argc, char* argv[])
{
transfer_tb T_tb1("transfer_tb");
sc_start(1000, SC_NS);
return 0;
}
what_got is not being initialized.