LRU c++ program - c++

I've been working on a program in one of my college classes. I have been having trouble with the implementation of my LRU code as it is not displaying any errors or anything, but compiles. There are two parts. The main that we input the values into, which we then specify which algorithm we want to use to find page faults. I know the main works, along with the FIFO algorithm, but I'm not getting anything with my LRU code (It compiles and "runs" but displays nothing as if I did not click to use the algorithm). Can anyone help me figure out what is wrong?
main.cpp
#include <iostream>
#include <string>
//#include "fifo.cpp"
#include "lru.cpp"
//#include "optimal.cpp"
using namespace std;
int main() {
// List of different variables
string pagestring;
int fs,pn[50], n;
// Prompt for page references
cout<<"Virtual Memory Simulation\nBy blah\n----------\nEnter the number of pages : " << endl;
cin >> n;
cout<<"\n-------------\nPlease enter a list of page numbers separated by commas.\n"<< endl;
cin>>pagestring;
// algorithm to use
char algo;
while (true) {
// Prompt algorithm to use
cout<<"----------\nPlease select an algorithm to use.\n\n1: First-In-First-Out (FIFO)\n2: Least-Recently-Used (LRU)\n3: Optimal\n0: Quit\n"<<endl;
cin>>algo;
if (algo == '1') {
//fifo(pagestring);
}
else if (algo == '2'){
LRU_Execute(pagestring, n);
}
else if (algo == '3'){
cout<<"Optimal Not yet coded"<<endl;
}
else if (algo == '0'){
break;
}
else {
cout<<"Invalid choice. Please try again."<<endl;
}
}
cout<<"Goodbye!!"<<endl;
};
LRU.cpp
#include <iostream>
#include <string>
using namespace std;
class pra
{
int fs,z;
int frame[50], frame1[50][2], pn[50], n, cnt, p, x;
public:
pra();
void init(string pagestring);
void getdata(string pagestring, int n);
void lru(int* pn, int n, string pagestring);
};
pra::pra()
{
int i;
for (i = 0; i < fs; i++)
{
frame[i] = -1;
}
for (i = 0; i < fs; i++)
{
frame1[i][0] = -1;
frame1[i][1] = 0;
}
p = 0;
cnt = 0;
}
void pra::init(string pagestring)
{
int i;
for (i = 0; i < fs; i++)
{
frame[i] = -1;
}
for (i = 0; i < fs; i++)
{
frame1[i][0] = -1;
frame1[i][1] = 0;
}
p = 0;
cnt = 0;
}
void pra::getdata(string pagestring, int n)
{
fs=3;
// index to loop through input string
int i = 0;
// current input string character
char z = pagestring[i];
int x = 0;
//cout << "\nEnter the page numbers : ";
while (z != '\0'){
// skip over commas and spaces
if (!(z == ',')) {
pn[x] = z;
x++;
// cout<<pn[x]<<"-This is pn[x]\n";
}
z = pagestring[++i];
}
//cout<<pn[x]<<"-This is pn[x] AGAIN\n";
this->lru(pn, n, pagestring);
}
void pra::lru(int* pn, int n, string pagestring)
{
init(pagestring);
int ind = 0, fault = 0, pi = 0, j, fn;
char i, z;
p = 0;
cnt = 0;
int min;
cout<<n<<"---"<<i<<" - "<<j<<" - "<<" - "<<fn<<" - "<<z;
for (i = 0; i < fs; i++)
{
frame1[i][0] = -1;
frame1[i][1] = 0;
}
pi = 0;
for (i = 0; i < n; i++)
{
j = 0;
if (ind > fs - 1)
ind = 0;
fault = 1;
min = 999;
while (j < fs)
{
if (frame1[j][0] = pn[pi])
{
fault = 0;
p++;
frame1[j][1] = p;
goto l2;
}
if (frame1[j][1] < min)
{
min = frame1[j][1];
fn = j;
}
j++;
}
j = 0;
while (j < fs)
{
if (frame1[j][0] = -1)
{
fault = 1;
fn = j;
goto l2;
}
j++;
}
ind++;
l2:
if (fault == 1)
{
p++;
frame1[fn][0] = pn[pi];
frame1[fn][1] = p;
cnt++;
}
cout << "\nElement: " << pn[pi];
pi++;
for (z = 0; z < fs; z++)
{
cout << "\t" << frame1[z][0];
}
if (fault == 1)
cout << "\t**Page Fault**";
else
cout << "\t--No Page Fault--";
}
cout << "\nTotal number of page faults: " << cnt;
cout << "\n";
}
void LRU_Execute(string pagestring, int n)
{
pra p;
int j, fault = 0, i, pi, z, fn, ind = 0, ans, ch;
p.getdata(pagestring, n);
//p.lru();
while (ans == 1);
//return 1;
}

Related

Implicit conversion from char* to bool

I managed to solve my problem, it working properly and giving the correct results. The problem now is that I have this warning: Implicit conversion from char* to bool[readability-implicit-bool-conversion].
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
bool is_letter(const char s) {
return ('a' <= s && s <= 'z') || ('A' <= s && s <= 'Z');
}
int main() {
const int MAX_LENGTH = 260;
const int VOWELS = 11;
char is_vowel[VOWELS] = "aeiouAEIOU", s[MAX_LENGTH];
ifstream fin("date.in");
int k;
cin >> k;
int start = -1,nrVowels = 0, finish = 0, counter = 0;
while (!fin.eof()) {
fin.getline(s, MAX_LENGTH);
int n = strlen(s);
int have_word = 0;
for (int i = 0; i < n; ++i) {
if (is_letter(s[i])) {
have_word = 1;
if (strchr(is_vowel, s[i])) {
++nrVowels;
}
if (counter == 0) {
start = i;
finish = i;
++counter;
} else {
finish = i;
}
} else if (have_word == 1) {
if (nrVowels >= k) {
for (int i = start; i <= finish; ++i) {
cout << s[i];
}
cout << "\n";
}
counter = 0;
have_word = 0;
nrVowels = 0;
}
}
if (have_word == 1) {
if (nrVowels >= k) {
for (int i = start; i <= finish; ++i) {
cout << s[i];
}
cout << "\n";
}
counter = 0;
nrVowels = 0;
finish = 0;
}
}
return 0;
}
The error appears on the line where I am searching for the vowels
"
if (strchr(is_vowel, s[i]))
"
strchr() returns a char *. You're then using it in a boolean operation. While it works, the compiler is suggesting you change the code to:
if (strchr(...) != nullptr)
Then there is no implicit conversion.
Note that there are people who think C++ implicit conversion should be removed. Jason Turner has a talk on this on YouTube. I have no idea how many bugs I've had over the years due to implicit conversion, which is why your compiler warns you about it.

My bubble sort is introducing values of '0' in array

I used a 'bubble-sort' for my C++ program, but it introduces random '0' values in array in a Fractional Greedy Program
int sorteaza()
{
int aux,schimb,i;
do
{
schimb=0;
for (i=0;i<=n;++i)
if (G[i][3]<G[i+1][3])
{
swap(G[i], G[i+1]);
}
}
while (schimb);
}
This is my entire code:
#include<iostream>
using namespace std;
int n; // Numarul de elemente
float G[100][3]; // Obiecte + detalii masa profit potenta
int masa = 0;
int read_data()
{
cout << "Greutatea Rucsac" << endl;
cin >> masa;
cout << "Obiecte: " << endl;
cin >> n;
for(int i = 1; i<=n;i++)
{
for(int j = 1; j<=2;j++)
{
cin >> G[i][j];
if(G[i][1] != 0 && G[i][2] != 0)
{
G[i][3] = G[i][2] / G[i][1];
}
}
}
}
// 2 500
// 4 500
int sorteaza()
{
int aux,schimb,i;
do
{
schimb=0;
for (i=0;i<=n;++i)
if (G[i][3]<G[i+1][3])
{
swap(G[i], G[i+1]);
}
}
while (schimb);
}
int verify()
{
for(int i = 1; i<=n;i++)
{
for(int j = 1; j<=3;j++)
{
cout << G[i][j];
cout << endl;
//G[i][3] = G[i][1] / G[i][2];
}
}
}
int greedy()
{
float profit = 0;
int i = 1;
int aux;
while(i<=n && masa>=0)
{
//cout << "G[i][1]: " << G[i][1] << endl;
if(masa>=G[i][1]) {
//cout << "Am ajuns aici";
profit=profit+G[i][2];
masa=masa-G[i][1];
}
else {
//cout << "Am ajuns dincolo";
aux= (masa*100)/G[i][1];
profit = profit + (aux * G[i][2])/100;
break;
}
i++;
}
cout << profit;
}
int main()
{
read_data();
sorteaza();
verify();
// greedy();
}
Learn to index all your arrays from zero.
float G[100][3];
Legal indexes are 0 to 99 and 0 to 2. So this code should be
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 2; j++)
{
cin >> G[i][j];
}
if (G[i][0] != 0 && G[i][1] != 0)
{
G[i][2] = G[i][1] / G[i][0];
}
}
and this code should be
if (G[i][2] < G[i+1][2])
{
swap(G[i], G[i+1]);
}
All your arrays start at zero. I'm sure you've been told this, but you have to start putting it into practise.
In general, write your for loops like this
for (int i = 0; i < N; ++i)
That's the correct loop for an array of size N.
You probably need <n instead of ≤n (that's where the uninitialized value i.e. 0 comes from). And you miss one loop in the bubble sort. Right now you're only bubbling the smallest element to the end of the list.
Also no idea what you're doing with that schimb and while condition.
Furthermore you're defining G as float[100][3] so you can't use G[i][3], only G[i][2].
int sorteaza()
{
int i,j;
for (i=0; i<n; i++)
{
for (j=i+1; j<n; j++)
{
if (G[i][2] < G[j][2])
{
swap(G[i], G[j]);
}
}
}
}

C++ Recursion to detect duplicates in row and column of grid

I'm coding a recursive algorithm to take a user input N and make a N x N grid where the same number does not appear twice on either a row or a column. Almost everything's working, and duplicates don't appear in columns, but I'm having trouble getting rows working.
My code for checking duplicates in rows is the function noRowDuplicates. Duplicates are still appearing, and occasionally it'll throw a segmentation fault, but I'm not sure why.
Thanks in advance for the help!
// Author: Eric Benjamin
// This problem was solved using recursion. fill() is the recursive function.
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
void fillOptions();
void fill(int arrayPosition);
int inputNum;
int gridSize;
int *grid;
int allOptionsSize = 0;
int *allOptions;
int main() {
cout << "Please enter a number!" << endl;
cin >> inputNum;
gridSize = inputNum * inputNum;
grid = new int[gridSize];
allOptions = new int[inputNum];
for (int i = 0; i < inputNum; i++) {
allOptions[i] = i + 1;
allOptionsSize++;
}
srand((unsigned)time(0));
fill(0);
delete[] grid;
delete[] allOptions;
return 0;
}
bool noColumnDuplicates(int arrPosition, int valueToCheck) {
for (int i = 1; i < inputNum; i++) {
if (arrPosition - (inputNum * i) >= 0) {
if (grid[arrPosition - (inputNum * i)] == valueToCheck) {
return false;
}
}
}
return true;
}
bool noRowDuplicates(int arrPosition, int valueToCheck) {
int rowPosition = arrPosition % inputNum; // 0 to num - 1
if (rowPosition > 0) {
for (int p = 1; p < rowPosition; p++) {
if (grid[arrPosition - p] == valueToCheck) {
return false;
}
}
}
return true;
}
void fill(int arrayPosition) {
if (arrayPosition < gridSize) {
int randomPosition = rand() % allOptionsSize;
grid[arrayPosition] = allOptions[randomPosition];
if (noColumnDuplicates(arrayPosition, grid[arrayPosition])) {
if (noRowDuplicates(arrayPosition, grid[arrayPosition])) {
if (arrayPosition % inputNum == 0) {
cout << endl;
}
cout << grid[arrayPosition] << " ";
fill(arrayPosition + 1);
} else {
fill (arrayPosition);
}
} else {
fill(arrayPosition);
}
}
}
noRowDuplicates never tests the first element of a row, which makes sense when you are trying to fill the first element of a row, but not any other time.

Simple program crashes for some reason

I wrote simple binary calculator,which I'm going to develop.Everything works for a few first calculations,but after that the program chrashes-"Binary.exe has stopped working".I think there might be something wrong with dynamicly allocated array in function "decToBin()",but i can't spot the issue.Here's the code:
#include <iostream>
#include <math.h>
#include <string>
#include <conio.h>
using namespace std;
void binToDec()
{
string bin;
cout<<"Binary code: ";
cin>>bin;
int powr = 0;
int num = 0;
long long sum = 0;
for(int i=bin.size()-1; i>=0; i--)
{
if(bin[i] == '1')
{
num = 2;
}
else if(bin[i] == '0')
{
num = 0 ;
}
sum += pow(num,powr);
cout<<sum<<endl;
powr++;
}
cout<<"Decimal: "<<sum<<endl;
sum = 0;
powr = 0;
num = 0;
}
void decToBin()
{
int dec = 0;
cout<<"Decimal number or digit: ";
cin>>dec;
int i = 0;
int *numBin = new int[i];
while(dec > 0)
{
numBin[i] = dec%2;
dec = dec/2;
i++;
}
cout<<"Binary: ";
for(int j = i-1; j>=0; j--)
{
cout<<numBin[j];
}
cout<<"\n";
i = 0;
delete [] numBin;
}
int main()
{
//USER INPUT
int nav = 0;
while(true)
{
cout<<"\n";
cout << "1.Binary to decimal:"<<endl;
cout << "2.Decimal to binary:"<<endl;
cin>>nav;
switch(nav)
{
case 1:
{
binToDec();
break;
}
case 2:
{
decToBin();
break;
}
}
}
return 0;
}
Your problem:
int *numBin = new int[i]; //i is 0, then you add elements to it
An easy solution, use std::vector:
vector<int> numBin;
...
numBin.push_back(dec%2);
You don't have to worry about dynamic memory at all now.

Can't figure out Segmentation Fault for C++ code

My code is below. The problem happens when I try and run the addArray() function. I am completely new to C++ so I have no idea what a segmentation fault means.
I also know that there is probably a better way to initialize and return the 2d arrays, but I am slowly figuring that out.
My main problem now is the segmentation fault. I am guessing that it has something to do with how I am accessing the variables?
#include <iostream>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <iomanip>
#include <time.h>
#include <stdlib.h>
using namespace std;
int c, q, w, row, coll, quit, qq, opt;
int** arr1;
int** arr2;
int** ans;
//Method Prototypes
int menu();
inline int** getArray(int opt);
inline void printArray(int** arr, int height, int width);
void addArray();
void subtractArray();
void multiplyArrays();
void determArray();
void transposeArray();
void inverseArray();
//Prints out the menu for choosing which option to go with
int menu() {
cout << "Press 1 for Addition\n";
cout << "Press 2 for Subtraction\n";
cout << "Press 3 for Multiplication\n";
cout << "Press 4 for Determinant\n";
cout << "Press 5 for Transpose\n";
cout << "Press 6 for Inverse\n";
cout << "Press 0 to quit\n\n";
cin >> c;
return c;
}
//Main method
int main(void) {
cout << "C++ 2d Matrix Operations Menu\n";
c = menu();
while (c != 0) {
if (c == 1) {
addArray();
} else if (c == 2) {
subtractArray();
} else if (c == 3) {
void multiplyArrays();
} else if (c == 4) {
void determArray();
} else if (c == 5) {
void transposeArray();
} else if (c == 6) {
}
c = menu();
}
cout << "Press Enter to Quit. GOOD BYE";
cin >> quit;
return 0;
}
/*
Prints out the specified array.
It's arguments are the actual array and the height/weight
*/
inline void printArray(int** arr, int height, int width) {
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
std::cout << arr[i][j] << ' ';
}
std::cout << std::endl;
}
}
//Returns an array.
inline int** getArray(int opt) {
if (opt == 0) {
cout << "How many rows and columns should be in the array?\n";
cin >> q >> w;
} else {
q = 3;
w = 3;
}
int** ary = new int*[q];
for (int i = 0; i < q; ++i) {
ary[i] = new int[w];
}
for (row = 0; row < q; row++) {
for (coll = 0; coll < w; coll++) {
cout << "What should the value be for item" << row << "," << coll << "\n";
cin >> ary[row][coll];
}
}
return ary;
}
//Adds arrays
void addArray() {
arr1 = getArray(0);
int h1 = q;
int w1 = w;
arr2 = getArray(0);
int h2 = q;
int w2 = w;
if ((h1 != h2) || (w1 != w2)) {
cout << "Both arrays must be the same size.";
return;
}
for (row = 0; row < q; row++) {
for (coll = 0; coll < w; coll++) {
ans[row][coll] = arr1[row][coll] + arr2[row][coll];
}
}
printArray(ans, q, w);
}
//Subtracts Arrays
void subtractArray() {
arr1 = getArray(0);
int h1 = q;
int w1 = w;
arr2 = getArray(0);
int h2 = q;
int w2 = w;
if ((h1 != h2) || (w1 != w2)) {
cout << "Both arrays must be the same size.";
return;
}
for (row = 0; row < q; row++) {
for (coll = 0; coll < w; coll++) {
ans[row][coll] = arr2[row][coll] - arr1[row][coll];
}
}
printArray(ans, q, w);
}
//Calculate the determinate of an array.
void determArray() {
arr1 = getArray(1);
printArray(arr1, q, w);
//There must be a better/more efficient way to do this using loops.
int determinant = arr1[0][0]*((arr1[1][1] * arr1[2][2]) - (arr1[2][1] * arr1[1][2])) - arr1[0][1]*(arr1[1][0] * arr1[2][2] - arr1[2][0] * arr1[1][2]) + arr1[0][2]*(arr1[1][0] * arr1[2][1] - arr1[2][0] * arr1[1][1]);
printf("\nDeterminant of vector using method 1 is: %d\n", determinant);
}
//Transpose an array.
void transposeArray() {
cout << "IN TRANS";
arr1 = getArray(0);
printArray(arr1, 3, 3);
//Flip the values
for (row = 0; row < q; row++) {
for (coll = 0; coll < w; coll++) {
ans[row][coll] = arr1[coll][row];
}
}
cout << "----------" << endl << "The new vector looks like: \n";
printArray(ans, q, w);
}
/*
Multiply arrays. One option is to just multiply it by a number and the other is to multiply it by another array.
*/
void multiplyArrays() {
arr1 = getArray(0);
int h1 = q;
int w1 = w;
cout << "Do you wish to multiply the first vector by a number(Enter 1), or by a second vector(Enter 2)?";
cin >> qq;
int mu;
//First Option is to multiply it by a single number
if (qq == 1) {
cout << "What number do you wish to multiply the vector by?";
cin >> mu;
for (row = 0; row < q; row++) {
for (coll = 0; coll < w; coll++) {
ans[row][coll] = arr1[row][coll] * mu;
}
}
printArray(ans, h1, w1);
//Multiply two arrays
} else if (qq == 2) {
arr2 = getArray(0);
int h2 = q;
int w2 = w;
int n1 = h1;
int n2 = w2;
int nCommon = n1;
if (n2 == nCommon) {
cout << "Amount of columns for vector 1 must match amount of rows for vector 2";
return;
}
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n2; j++) {
for (int k = 0; k < nCommon; k++) {
ans[i][j] += arr1[i][k] * arr2[k][j];
}
}
}
printArray(ans, n1, n2);
}
}
You never allocate memory for ans. Just like you need to allocate storage for the two input arrays before filling them, you need to allocate storage for the answer.
A segmentation fault is generated when you attempt to write to memory that you do not have access to. In this case, because the ans array was not initialized, it points to random memory. When you do ans[row][coll] = arr2[row][coll] - arr1[row][coll];, you get a segfault because ans[row][col] is pointing somewhere outside your program space.
The problem is that you have not allocated memory for the ans array, but you are writing to it in the following code:
for (row = 0; row < q; row++) {
for (coll = 0; coll < w; coll++) {
ans[row][coll] = arr2[row][coll] - arr1[row][coll];
}
}
This is why you have segmentation fault.
Try to add a block to allocate memory for ans at first.