I was confused from this following codes, it's creating crash that I fully don't understand.
#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;
struct Store
{
int pos;
char character;
};
vector<struct Store> v_store;
void swap_inside_vector(vector<struct Store> &v_store, int a, int b)
{
struct Store tmp = v_store[b];
v_store[b] = v_store[a];
v_store[a] = tmp;
}
int find_inside_vector(vector<struct Store> &v_store, int pos)
{
for(int i = 0; i < v_store.size(); i++)
{
if(v_store[i].pos == pos)
return i;
}
return -1;
}
void swap_most_right_to_most_left(vector<struct Store> &v_store)
{
struct Store tmp = v_store[v_store.size() - 1];
for(int i = v_store.size(); i > 0; i--)
{
v_store[i] = v_store[i-1];
}
v_store[0] = tmp;
}
void print_char_inside_vector(vector<struct Store> &v) // used for debugging
{
for(int i = 0; i < v.size(); i++)
{
printf("%C", v[i].character);
}
}
int check_vector_original_state(vector<struct Store> &v_store)
{
for(int i = 1; i <= v_store.size(); i++)
{
if(v_store[i-1].pos != i)
return 0;
}
return 1;
}
int main()
{
int n;
char input_str[100];
for(int q = 1; scanf("\n%d", &n), n; q++)
{
scanf("%s", input_str);
vector<struct Store> original_store, tmp_origin_store, v_store;
vector<vector<struct Store> > store_vector;
original_store.clear();
tmp_origin_store.clear();
v_store.clear();
store_vector.clear();
for(int i = 1; i <= strlen(input_str); i++)
{
struct Store s = {.pos = i, .character = input_str[i-1]};
original_store.push_back(s);
}
tmp_origin_store = original_store;
v_store = tmp_origin_store;
for(int i = 1, current_pos = 0; i <= n; i++, current_pos++)
{
int vector_index = find_inside_vector(v_store, tmp_origin_store[current_pos].pos);
//printf("Processing -> [%d], Current Pos -> [%d]\n", i, current_pos);
for(int z = 0; z < (current_pos + 1); z++)
{
if(vector_index == (v_store.size() - 1))
{
swap_most_right_to_most_left(v_store);
vector_index = 0;
}
else
{
swap_inside_vector(v_store, vector_index, vector_index + 1);
vector_index++;
}
//print_char_inside_vector(v_store);
//puts("");
}
//puts("");
store_vector.push_back(v_store);
if(check_vector_original_state(v_store))
{
store_vector.push_back(v_store);
break;
}
if(current_pos == (v_store.size() - 1))
{
tmp_origin_store = v_store;
current_pos = -1;
}
}
// debugging
/*for(int x = 0; x < store_vector.size(); x++)
{
printf("[%d] -> ", x + 1);
print_char_inside_vector(store_vector[x]);
puts("");
}*/
int target_pos;
if(store_vector.size() < n)
{
target_pos = n % store_vector.size();
}
else
{
target_pos = store_vector.size();
}
if(target_pos == 0)
{
printf("%d. ", q);
print_char_inside_vector(store_vector[0]);
puts("");
}
else
{
printf("%d. ", q);
print_char_inside_vector(store_vector[target_pos - 1]);
puts("");
}
}
}
What this program does is accepting input from STDIN, process it, and output it on STDOUT.
My expecting input is
3 ABCD
13 ACM
3 DAEQD
4 FAEQS
Expected output is
1. CABD
2. CAM
3. DAQDE
4. FQASE
My problem is, after inputing fourth input into STDIN, and after output is being shown, crash occured.
C:\Study>h.exe
3 ABCD
1. CABD
13 ACM
2. CAM
3 DAEQD
3. DAQDE
4 FAEQS
4. FQASE
0 [main] h 9092 cygwin_exception::open_stackdumpfile: Dumping stack trace to h.exe.stackdump
From my observation, I think the problem is at the vector, but it's just a guess.
Your code didn't compile :
//struct Store s = { .pos = i, .character = input_str[i - 1] }; // syntax not recongnized
Store s = { i, input_str[i - 1] }; // replaced with this.
After fixing this, the debugging immediatly identified an out of bound problem on a vector, which could lead to memory corruption issue. It's in swap_most_right_to_most_left():
for (int i = v_store.size(); i > 0; i--) { // you start with i=v_store.size()
v_store[i] = v_store[i - 1]; // and you immediately get out of bounds !
}
If you correct this instruction to :
for (int i = v_store.size()-1; i > 0; i--) {
v_store[i] = v_store[i - 1];
}
you'll get the expected output for the given input.
Related
Please guys I need some help. I get Warning C6386 Buffer overrun while writing to 'AnArray': the writable size is 'nrows*8' bytes, but '16' bytes might be written. on the following code
#include <math.h>
void SubMain(int, int);
int CSTEBit(int, int, int);
double Fact(int);
double Perm(int, int);
int Comb(int, int);
int main()
{
SubMain(13, 5);
}
void SubMain(int N, int R)
{
int** AnArray;
int nrows = Comb(N, R) + 1;
int ncolumns = 8;
int Pos;
int Count;
AnArray = new int* [nrows];
for (int i = 0; i < nrows; i++)
AnArray[i] = new int[ncolumns];
for (int a = 0; a < nrows; a++)
{
for (int b = 0; b <= 7; b++)
AnArray[a][b] = 0;
}
Pos = 0;
Count = 0;
do
{
Pos += 1;
if ((CSTEBit(3, AnArray[Pos][7], 4) == 0) && (CSTEBit(3, AnArray[Pos][7], 5) == 0))
Count += 1;
} while (Count != nrows - 1);
AnArray[Pos][7] = CSTEBit(1, AnArray[Pos][7], 4);
}
int CSTEBit(int CSTE, int Byt, int Bit)
{
int tempCSTEBit = 0;
if (Bit < 8)
{
int Mask = (int)pow(2, Bit);
switch (CSTE)
{
case 0:
tempCSTEBit = (int)(Byt && ~Mask);
break;
case 1:
tempCSTEBit = (int)(Byt | Mask);
break;
case 2:
tempCSTEBit = (int)(Byt ^ Mask);
break;
case 3:
if ((Byt & Mask) > 0)
{
tempCSTEBit = 1;
}
else
{
tempCSTEBit = 0;
}
break;
default:
tempCSTEBit = Byt;
break;
}
}
else
{
tempCSTEBit = Byt;
}
return tempCSTEBit;
}
double Fact(int N)
{
double tempFact = 0;
if (N <= 1)
{
tempFact = 1;
}
else
{
tempFact = N * Fact(N - 1);
}
return tempFact;
}
double Perm(int N, int R)
{
double tempPerm = 0;
int a = 0;
double b;
b = 1;
if (N < R)
{
tempPerm = 0;
}
else
{
for (a = (N - (R - 1)); a <= N; a++)
{
b = b * a;
}
tempPerm = b;
}
return tempPerm;
}
int Comb(int N, int R)
{
int tempComb = 0;
if (N < R)
{
tempComb = 0;
}
else
{
tempComb = (int)(Perm(N, R) / Fact(R));
}
return tempComb;
}
The variable Pos will never be higher than what Comb function returns which is used to initialize the AnArray. Thanks in advance for any answer.
Well actually I insert "if (Pos < nrows)" inside the do loop after Pos += 1; and the warning was gone.
I'm working on a coding assignment for a C++ class. When I run my program I seem to be dealing with a memory leakage issue, which is weird since I am NOT explicitly allocating any memory in my code. I ran the program under gdb, and it seems as though the program crashes when running the destructor for a Deck object. I tried stepping through the code, but I when I do so I end up in a host of .h files related to vectors. Then suddenly, it stops. I tried going to a TA for some help, but they seem to be as perplexed as I am on the issue.
# include <stdlib.h>
# include <time.h>
# include <iostream>
# include <vector>
# include <stdio.h>
using namespace std;
//function signatures
float bustProbability (const int);
class Deck
{
public:
//data members
vector <int> cardArray;
vector <int> wasteCards;
//constructor
Deck();
//methods
void shuffleDeck();
void populateDeckWithCards();
void removeCopyCards();
int dealCard();
int remainingCards();
void showCards();
};
void Deck::removeCopyCards() {
for (unsigned int i = 0; i < wasteCards.size(); i++) {
bool removedCopy = false;
for (unsigned int j = 0; j < cardArray.size() && removedCopy == false; j++) {
if (cardArray[j] == wasteCards[i]) {
cardArray.erase (cardArray.begin() + j - 1);
removedCopy = true;
}
}
}
}
int Deck::dealCard() {
if (remainingCards() > 0) {
int tmp = cardArray.back();
wasteCards.push_back(tmp);
cardArray.pop_back();
return tmp;
}
else {
populateDeckWithCards();
removeCopyCards();
shuffleDeck();
//shuffle method
int tmp = cardArray.back();
cardArray.pop_back();
return tmp;
}
}
void Deck::populateDeckWithCards() {
//populate regular cards into array
for (int i = 2; i <= 10; i++) {
for (int j = 0; j < 4; j++) {
cardArray.push_back(i);
}
}
//populate J, Q, K into array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
cardArray.push_back(10);
}
}
//populating array with Aces... treating them as special case '100'
for (int i = 0; i < 4; i++) {
cardArray.push_back(100);
}
return;
}
void Deck::showCards() {
for (unsigned int i = 0; i < cardArray.size(); i++) {
cout << cardArray[i] << endl;
}
}
Deck::Deck() {
wasteCards.clear();
cardArray.clear();
populateDeckWithCards();
shuffleDeck();
}
void Deck::shuffleDeck() {
int n = cardArray.size();
for(int a = n-1; a > 0; a--) {
int min = 0;
int max = a;
int j = min + rand() / (RAND_MAX / (max-min + 1) + 1);
int tmp = cardArray[a];
cardArray[a] = cardArray[j];
cardArray[j] = tmp;
}
return;
}
int Deck::remainingCards() {
return cardArray.size();
}
class Player {
public:
//data members
vector <int> playerHand;
//constructor
Player();
//methods
bool isBust();
int count();
void hit(Deck&);
void stand();
bool muckHand();
void showHand();
};
Player::Player() {
playerHand.clear();
}
void Player::showHand() {
for (unsigned int i = 0; i < playerHand.size(); i++) {
cout << playerHand[i] << endl;
}
return;
}
int Player::count() {
int handCount = 0;
for (unsigned int i = 0; i < playerHand.size(); i++) {
if (playerHand[i] != 100)
handCount += playerHand[i];
else {
if (playerHand[i] == 100) {
if ((handCount) > 11) {
handCount += 1;
}
else
handCount += 10;
}
}
}
return handCount;
}
bool Player::isBust() {
if (count() > 21)
return true;
else
return false;
}
void Player::hit(Deck& d) {
playerHand.push_back(d.dealCard());
}
void Player::stand() {
return;
}
bool Player::muckHand() {
playerHand.clear();
return true;
}
float bustProbability (const int threshHold) {
int threshHoldReached = 0;
Deck myDeck;
Player myPlayer;
Player dealer;
for (int i = 0; i < 10000; i++) {
myPlayer.hit(myDeck);
dealer.hit(myDeck);
myPlayer.hit(myDeck);
dealer.hit(myDeck);
while (myPlayer.count() < threshHold) {
myPlayer.hit(myDeck);
}
if (!(myPlayer.isBust())) {
++threshHoldReached;
}
myDeck.wasteCards.clear();
myPlayer.muckHand();
dealer.muckHand();
}
float bustFraction = float(threshHoldReached)/float(10000);
return bustFraction;
}
int main () {
cout << "blackjack simulation" << endl;
srand((unsigned int)time(NULL));
cout << bustProbability(19);
return 0;
}
I'm incredibly sorry for just posting my code, but I've spend 4 days on this issue, and I can't even begin to figure out what the problem is.
There is at least the line
cardArray.erase (cardArray.begin() + j - 1);
which seems to be dubious in case of j = 0
I have a double pointer boolean.
I would like to pass this boolean to a function
The code is used for graph theory, to create an adj matrix, check if the graph has cycles or not ...
The problem comes from the cycle function
The function doesn't like the boolean in parameter to check if a graph has a cycle.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;
int Cycle(int number_of_vertices ,bool **adj_matrix)
{
bool** adj = new bool*[number_of_vertices];
for(int i=0;i<number_of_vertices;i++)
{
adj[i] = new bool[number_of_vertices];
}
for(int i=0;i<number_of_vertices;i++)
{
for(int j=0;j<number_of_vertices;j++)
{
adj[i][j] = adj_matrix[i+1][j+1];
}
}
for(int k=0;k<number_of_vertices;k++)
{ // transitiv closure
for(int i=0;i<number_of_vertices;i++)
{
for(int j=0;j<number_of_vertices;j++)
{
if(adj[i][k]&&adj[k][j])
{
adj[i][j] = true;
}
}
}
}
int count = 0;
for(int i=0;i<number_of_vertices;i++)
{
if(adj[i][i])
{
count++;
}
}
return count;
}
int main()
{
string first_line, second_line;
int initial_extremity, final_extremity, value, number_of_vertices, nombre_arcs;
ifstream fichier("test.txt");
bool** adj_matrix;
int** val_matrix;
vector<int> vertice_names;
if (fichier.is_open())
{
getline(fichier, first_line);
number_of_vertices = atoi(first_line.c_str());
getline(fichier, second_line);
nombre_arcs = atoi(second_line.c_str());
adj_matrix = new bool*[number_of_vertices];
val_matrix = new int*[number_of_vertices];
for (int i=0; i<number_of_vertices;i++)
{
adj_matrix[i] = new bool[number_of_vertices];
val_matrix[i] = new int[number_of_vertices];
for (int j=0; j<number_of_vertices; j++)
{
adj_matrix[i][j] = false;
val_matrix[i][j] = 0;
}
}
while(fichier >> initial_extremity >> final_extremity >> value)
{
adj_matrix[initial_extremity][final_extremity] = true;
val_matrix[initial_extremity][final_extremity] = value;
int c = Cycle(number_of_vertices, adj_matrix);
printf("number of cycles: %d\n\n", c);
if(c!=0)
{
printf("%d --[%d]--> %d\n",initial_extremity,value,final_extremity);
}
else
{
printf("%d --[%d]--> %d\n",initial_extremity,value,final_extremity);
}
if ( find(vertice_names.begin(), vertice_names.end(), initial_extremity) != vertice_names.end() )
{
//nothing
}
else
{
vertice_names.push_back(initial_extremity);
}
if ( find(vertice_names.begin(), vertice_names.end(), final_extremity) != vertice_names.end() )
{
//nothing
}
else
{
vertice_names.push_back(final_extremity);
}
}
fichier.close();
}
else
{
cout << "error while opening the file" << '\n';
cin.get();
}
printf("%d arcs\n",nombre_arcs);
printf("%d vertices\n\n\n",number_of_vertices);
printf("Adj Matrix \n");
printf(" ");
for(int i = 0; i<number_of_vertices; i++)
{
printf("%3d",vertice_names.at(i));
}
printf("\n");
for (int i = 0; i<number_of_vertices; i++)
{
printf("%3d ", vertice_names.at(i));
for (int j = 0; j <number_of_vertices; j++)
{
printf("%3d",adj_matrix[i][j]);
}
printf("\n");
}
printf("\n\n");
sort(vertice_names.begin(), vertice_names.end(), less<int>());
printf("Adj and value matrix\n");
printf(" ");
for(int i = 0; i<number_of_vertices; i++)
{
printf("%3d",vertice_names.at(i));
}
printf("\n");
for (int i = 0; i<number_of_vertices; i++)
{
printf("%3d ", vertice_names.at(i));
for (int j = 0; j <number_of_vertices; j++)
{
if (adj_matrix[i][j])
{
printf("%3d",val_matrix[i][j]);
}
else
{
printf(" ");
}
}
printf("\n");
}
return 0;
}
format of the .txt file:
first line : number of vertices
second : number of arcs
the other lines : Inital Arc Final Arc Value
3
4
0 1 0
1 0 12
1 2 25
2 0 6
By the way, if someone have a better idea to check if a graph has a cycle let me know
Best regards
Looks to me like you are stepping out of bounds in the Cycle function:
for(int i=0;i<number_of_vertices;i++)
{
for(int j=0;j<number_of_vertices;j++)
{
adj[i][j] = adj_matrix[i+1][j+1]; // i + 1 and j + 1 go out of bounds
}
}
Suppose number_of_vertices is 3. Then the index of the last element is 2. When i = 2, then i + 1 = 3. Out of bounds.
I have the graph with N nodes. I have to create the longest subgraph (with max nodes). One node can be connected with only 2 nodes. So which nodes should I take to create this (max) subgraph?
What I'm doing is:
1: From initial node. I start 2 DFS functions. (from anothers nodes only 1).
2: For some node in DFS I use F() function to check all neighbours and find maximum way that I have to go. Then I'm saving the index of the node in which I have to go in index variable and starting DFS from index.
The problem is that this algorithm is too slow. How can I optimize it? Maybe there is special algorithm to find maximum subgraph?
Here is my code:
#include <stdio.h>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
int used[20];
int m[20][20];
int c;
int F(int v) {
used[v] = 1;
int maxn = 0, index = -1, t;
for(int i = 0; i < c; ++i) {
if(!used[i] && m[v][i] == 1) {
t = F(i);
if(t > maxn) {
maxn = t;
index = i;
}
}
}
if(index != -1) {
used[v] = 0;
return maxn + 1;
}
else {
used[v] = 0;
return 1;
}
}
int DFS(int v) {
used[v] = 1;
int maxn = 0, index = -1, t;
for(int i = 0; i < c; ++i) {
if(!used[i] && m[v][i] == 1) {
t = F(i);
if(t > maxn) {
maxn = t;
index = i;
}
}
}
if(index != -1) {
return DFS(index) + 1;
}
else {
return 0;
}
}
int main() {
cin >> c;
for(int i = 0; i < c; ++i) {
for(int j = 0; j < c; ++ j)
cin >> m[i][j];
}
int maxn = DFS(0) + DFS(0) + 1;
cout << maxn << endl;
}
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int arraylength;
int lastbig = 0;
int lastsmall = 0;
int temp = 0;
int numofgroups = 0;
double gg = 0;
cout<<"Enter the number of numbers you are going to enter "<<endl;
cin>>arraylength;
int data[arraylength];
for(int ahmet = 0;ahmet < arraylength;ahmet++)
{
cout<<"Enter the num no."<<ahmet+1<<endl;
cin>>data[ahmet];
}
for(int bbm = 0;bbm < arraylength;bbm++)
{
if(data[bbm]>lastbig)
{
lastbig = data[bbm];
}
}
cout<<"Biggest "<<lastbig<<endl;
for(int ddr = 0;ddr < arraylength;ddr++)
{
if(data[ddr]<lastbig && lastsmall == 0)
{
lastsmall = data[ddr];
}
else if(data[ddr]<lastsmall)
{
lastsmall = data[ddr];
}
}
cout<<"smallest "<<lastsmall<<endl;
temp = lastbig-lastsmall;
cout<<"Enter the number of groups you want"<<endl;
cin>>numofgroups;
gg = (double)temp/numofgroups;
cout<<"gg ="<<gg;
gg = ceil(gg);
cout<<"gg ="<<gg<<endl;
int z = 0;
int lastnumleft = 0;
struct groups {
int min;
int max;
int membercount;
}group[numofgroups];
int tmp = lastsmall;
for(int dinghy = 0;dinghy<numofgroups;dinghy++)
{
if(dinghy == 0)
{
group[dinghy].min = tmp;
group[dinghy].max = tmp + ((int)gg - 1);
tmp = tmp + (int)gg;
}
else{
group[dinghy].min = tmp;
group[dinghy].max = tmp+((int)gg-1);
tmp = tmp + (int)gg;
}
}
for(int jpn = 0;jpn<numofgroups;jpn++)
{
for(int mtr = 0;mtr<arraylength;mtr++)
{
if(data[mtr]>group[jpn].min&&data[mtr]<group[jpn].max)
{
group[jpn].membercount++;
}
}
}
for(int dingil = 0;dingil<numofgroups;dingil++)
{
if(!group[dingil].membercount){
group[dingil].membercount = 0;
}
}
for(int xyz = 0;xyz<numofgroups;xyz++)
{
cout<<group[xyz].min<<" - "<<group[xyz].max<<" "<<group[xyz].membercount<<endl;
}
cin.ignore();
cin.get();
return 0;
}
This program actually does the calculations needed for making a histogram member count of groups and min max of numbers but i cant group the numbers can you help me :)
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int arraylength;
int lastbig = 0;
int lastsmall = 0;
int temp = 0;
int numofgroups = 0;
double gg = 0;
cout<<"Enter the number of numbers you are going to enter "<<endl;
cin>>arraylength;
int *data = new int[arraylength];
for(int ahmet = 0;ahmet < arraylength;ahmet++)
{
cout<<"Enter the num no."<<ahmet+1<<endl;
cin>>data[ahmet];
}
for(int bbm = 0;bbm < arraylength;bbm++)
{
if(data[bbm]>lastbig)
{
lastbig = data[bbm];
}
}
cout<<"Biggest "<<lastbig<<endl;
for(int ddr = 0;ddr < arraylength;ddr++)
{
if(data[ddr]<lastbig && lastsmall == 0)
{
lastsmall = data[ddr];
}
else if(data[ddr]<lastsmall)
{
lastsmall = data[ddr];
}
}
cout<<"smallest "<<lastsmall<<endl;
temp = lastbig-lastsmall;
cout<<"Enter the number of groups you want"<<endl;
cin>>numofgroups;
gg = (double)temp/numofgroups;
cout<<"gg ="<<gg;
gg = ceil(gg);
cout<<"gg ="<<gg<<endl;
int z = 0;
int lastnumleft = 0;
struct groups {
int min;
int max;
int membercount;
}*group;
group = new groups[numofgroups];
int tmp = lastsmall;
for(int dinghy = 0;dinghy<numofgroups;dinghy++)
{
if(dinghy == 0)
{
group[dinghy].min = tmp;
group[dinghy].max = tmp + ((int)gg - 1);
tmp = tmp + (int)gg;
}
else
{
group[dinghy].min = tmp;
group[dinghy].max = tmp+((int)gg-1);
tmp = tmp + (int)gg;
}
}
for(int jpn = 0;jpn<numofgroups;jpn++)
{
//need to initialize as it has some garbage value and that is what it is printing out.
group[jpn].membercount = 0;
for(int mtr = 0;mtr<arraylength;mtr++)
{
// note the equalities as you need to include the first and the last numbers
if(data[mtr]>=group[jpn].min&&data[mtr]<=group[jpn].max)
{
group[jpn].membercount++;
}
}
}
for(int dingil = 0;dingil<numofgroups;dingil++)
{
if(!group[dingil].membercount){
group[dingil].membercount = 0;
}
}
for(int xyz = 0;xyz<numofgroups;xyz++)
{
cout<<group[xyz].min<<" - "<<group[xyz].max<<" "<<group[xyz].membercount<<endl;
}
cin.ignore();
cin.get();
return 0;
}
It'll work fine now :)