when i try to compile i keep getting message vector subscript out of range - c++

string getName() { return name; }
string getE1() { return enemy1; }
string getE2() { return enemy2; }
string getE3() { return enemy3; }
bool isEnemy(string check) {
if (check == enemy1 || check == enemy2 || check == enemy3)
//if the name being checked is an enemy of this knight
return true;
else
return false;
}
int Candidate(Knight b) {//'b' is an enemy of 'a' who is in the seat before 'b'(ie. b seat=2 a seat=1
int toSwap = b.seatingPos;//toSwap holds seating pos # of 'b'
int checkFriends = (toSwap - 1);//holds seating pos of 'a'
string nameA = table[checkFriends].getName();
for (int i = 0; i < 8; i++) {
if (table[i].isEnemy(nameA) || table[i].getName() == nameA) //if not enemies, then must be friends
{
continue;
}
else
{
friends.push_back(table[i].seatingPos);
}//adds seating # of friends of 'a' to friends vector
}
for (int j = 0; j < 4; j++) {//check friends of 'a' to see if their neighbor is friends with 'b'
int check2 = table[friends[j]].seatingPos;//check 2 holds seating pos # of 'c'
if (check2 != 7)
++check2;
else
return check2;
if ((table[toSwap].isEnemy(table[check2].getName()))) //if neighbor of c is friends with b(toSwap)
{
continue;
}
else {
return check2;//if not enemies then must be friends return seating pos of acceptable candidate
}
}
return 0;
}
when i debug the code it says i have an unhandled exception when assigning
string nameA = table[checkFriends].getName();
the value of checkfriends = 0 so it shouldnt be out of the range of the vector.
debugger also says: Unhandled exception at 0x7BC8F2F6 (ucrtbased.dll) in Knights.exe: An invalid parameter was passed to a function that considers invalid parameters fatal. occurred
this occurs during the 1st if statement.
thanks for any help!!!

Related

Why does my c++ code run fine on Windows 7 but crashes on Windows 8?

Ok, I added the following code to a mod menu for a game and everything works fine for me in Windows 7. But when I send it to my friend on Windows 8, he tries to select a button (which calls the GetClients() function) and the game just crashes. Any idea why?
char* playerNames[31] = {};
int getUID(char* pName)
{
int i = 0;
while (i < 31) {
char* pNamesec = (char*)PLAYER::GET_PLAYER_NAME((Player)(i));
if (pNamesec == pName) {
return i;
}
//else { break; }
i++;
}
}
char* getPnameAt(int id) {
for (int i = 0; i < 30; i++) {
if (i == id) {
return (char*)PLAYER::GET_PLAYER_NAME((Player)(i));
}
}
}
void GetClients()
{
playerNames[31] = {};
int i = 0;
while (i < 100) {
char* pName = (char*)PLAYER::GET_PLAYER_NAME((Player)(i));
if (wcslen((WCHAR*)pName) > 3) {
if (getUID(pName) == i) {
playerNames[i] = pName;
} else {
getPnameAt(i);
}
}
i++;
}
i = 0;
}
Error message that pops up says:
CORE: An exception occurred while executing modmenu.asi, press ok to continue
You have created an array of length 31. So you can access array playerName from index 0 to index 30. In GetClients()
playerNames[31] = {}; //Observe this line
while (i < 100) {
// Indexes greater than 30 are being used to access playerNames array
}
31 or beyond is not a valid index for playerNames array and you are getting undefined behavior.
So if you want to add in playerNames in runtime. Below is the small example that might help you..
int main()
{
vector<string> playerNames;
playerNames.push_back("XYZ");
playerNames.push_back("ABC");
// To access from vector
vector<string>::iterator itr = vec.begin();
for(;itr!=vec.end();itr++)
{
cout<<*itr<<endl;
}
}
Read more here

Error: not all control paths return a value

I am writing two functions in a program to check if a string has an assigned numeric code to its structure array or if the given numeric code has an assigned string in the same structure array. Basically, if I only know one of the two, I can get the other. I wrote the following:
int PrimaryIndex::check_title_pos(std::string title) {
bool findPos = true;
if (findPos) {
for (int s = 1; s <= 25; s++) {
if (my_list[s].title == title) {
return s;
}
}
} else {
return -1;
}
}
std::string PrimaryIndex::check_title_at_pos(int pos) {
bool findTitle = true;
if (findTitle) {
for (int p = 1; p <= 25; p++) {
if (my_list[p].tag == pos) {
return my_list[p].title;
}
}
} else {
return "No title retrievable from " + pos;
}
}
However, it says not all control paths have a return value. I thought the else {} statement would handle that but it's not. Likewise, I added default "return -1;" and "return "";" to the appropriate functions handling int and string, respectively. That just caused it to error out.
Any idea on how I can keep this code, as I'd like to think it works but cant test it, while giving my compiler happiness? I realize through other searches that it sees conditions that could otherwise end in no returning values but theoretically, if I am right, it should work fine. :|
Thanks
In the below snippet, if s iterates to 26 without the inner if ever evaluating to true then a return statement is never reached.
if (findPos) {
for (int s = 1; s <= 25; s++) {
if (my_list[s].title == title) {
return s;
}
}
}

How to change a value in an array C++

This function is for code to play a game of tic tac toe:
//--------------------FUNCTION--------------------
bool playCell(int player, int position, int gameBoard[]) {
if (gameBoard[position] == 10 || gameBoard[position] == 11) {
return false;
} else {
return true;
if (player == 0){
gameBoard[position] = 10;
} else {
gameBoard[position] = 11;
} // end if
}
} // end function
playCell takes a player (0 for "O", 1 for "X"), a position (1 to 9), and the nine element gameBoard, and returns true if the move is legal (i.e. that spot is not yet taken), and false otherwise. If the move is legal it changes the position to that players number (10 for "O", 11 for "X"). If the player or position input is invalid, it returns false.
I'm trying to figure out how to get the array to change its value to either a 10 or 11 depending on the player, and saving to the position they entered to play in.
The return keyword redirect the program flow back to the main program. So the code after return will not be executed. Change the position of return:
//--------------------FUNCTION--------------------
bool playCell(int player, int position, int gameBoard[])
{
if (gameBoard[position] == 10 || gameBoard[position] == 11)
{
return false;
}
else
{
if (player == 0)
{
gameBoard[position] = 10;
}
else
{
gameBoard[position] = 11;
} // end if
return true;
}
} // end function
You have a return statement prior to your array assignment here:
return true; // HERE
if (player == 0){
gameBoard[position] = 10;
} else {
gameBoard[position] = 11;
} // end if
this causes your code not to be executed. Remove this line from there and put in the correct place.

Access violation reading location 0x0000001

I have this function in c++ that should add a member to a linked list, but when it's executed it throw an exception:
Unhandled exception at 0x5b9414cf (msvcr100d.dll) in Sample.exe: 0xC0000005: Access violation reading location 0x00000001
This happen when some variable isn't definite...but I can't figure out where is this variable...also with breakpoints.
Here the entire code (except for the .h file...but it only contains declaration)
#include "stdafx.h"
#include "winsock.h"
#include "windows.h"
#include <string.h>
#include <iostream>
#include "Sample.h"
using namespace std;
struct BUNNY
{
public:
int sex;
int name;
int age;
bool colour;
int radioactive_mutant_vampire_bunny;
BUNNY *nextBunny;
};
int returnSex();
int returnName (int sex);
int returnColour ();
bool radioactiveBunny ();
string translateName(int name);
string translateSex(int sex);
string translateColour(int colour);
BUNNY * AddBunny(BUNNY * head,int sex,int name,int colour,bool radioactive_mutant_vampire_bunny);
BUNNY * travereseBunny(BUNNY * head);
BUNNY * displayBunny();
int _tmain(int argc, _TCHAR* argv[])
{
bool flag = true;
int turn = 0;
BUNNY * head = new BUNNY;
head = NULL;
while (flag)
{
++turn;
if (turn == 1)
{
for (int i = 1; i <= 5; i++)
{
int sex = returnSex();
int name = returnName(sex);
int colour = returnColour();
bool radioactive = radioactiveBunny();
head = AddBunny(head,sex,name,colour,radioactive);
printf("A new bunny is born: sex %s , name %s , colour %s , radioactive %d",head->sex,head->name,head->colour,head->radioactive_mutant_vampire_bunny);
system("pause");
}
}
}
return 0;
}
int returnSex()
{
int random = rand() % 100 + 1;
if(random > 50)
return MALE;
else
return FEMALE;
}
int returnName(int sex)
{
if (sex == MALE)
{
int random = (rand() % 100 + 1) / 5;
if(random < 20)
return BU;
else if (random > 20 && random <40)
return CRYSTAL;
else if(random > 40 && random < 60)
return JASON;
else if(random > 60 && random < 80)
return ERO;
else if(random > 80)
return METH;
}
else
{
int random1 = rand() % 100 + 1;
if (random1 < 50 )
{
return MARIA;
}
else if (random1 > 50)
return JAMIE;
}
}
int returnColour ()
{
int random = rand() % 4 + 1;
if(random == 1)
return WHITE;
else if(random > 1 && random <= 2)
return BROWN;
else if(random > 2 && random <= 3)
return BLACK;
else if(random > 3 && random <= 4)
return SPOTTED;
}
bool radioactiveBunny()
{
int random = rand() % 100 + 1;
if(random > 0 && random <= 2)
return true;
else
return false;
}
BUNNY * AddBunny(BUNNY * head,int sex,int name,int colour,bool radioactive_mutant_vampire_bunny)
{
BUNNY * newBunny = new BUNNY;
newBunny->age = 0;
newBunny->colour = colour;
newBunny->sex = sex;
newBunny->name = name;
newBunny->radioactive_mutant_vampire_bunny = radioactive_mutant_vampire_bunny;
newBunny->nextBunny = head;
return newBunny;
}
string translateName (int name)
{
switch (name)
{
case CRYSTAL: return "CRYSTAL";
break;
case BU: return "BU";
break;
case JASON: return "JASON";
break;
case ERO: return "ERO";
break;
case METH: return "METH";
break;
case MARIA: return "MARIA";
break;
case JAMIE: return "JAMIE";
break;
}
}
string translateColour (int colour)
{
switch (colour)
{
case WHITE: return "WHITE";
break;
case BLACK: return "BLACK";
break;
case BROWN: return "BROWN";
break;
case SPOTTED: return "SPOTTED";
break;
}
}
string translateSex (int sex)
{
switch (sex)
{
case MALE: return "MALE";
break;
case FEMALE: return "FEMALE";
break;
}
}
this is the entire code...hope it will help.
thanks for your time :)
Whether there is a probelm or no depends on how you call the function
It should be called the following way
head = AddBunny( /* some arguments */ );
If you call it such a way then there is no problem with the function.
If you call it as for example
AddBunny( /* some arguments */ );
that is without assigning head by the returning pointer then head will be always equal to NULL.
EDIT: After you showed additional code then I would like to point out that these statements
BUNNY * head = new BUNNY;
head = NULL;
are invalid. There is a memory leak. You at first allocate memory and head gets the address of the memory and then you reassign the head.
There must be
BUNNY * head = NULL;
Also it seems your code has a typo. You defined private data members as
bool colour;
int radioactive_mutant_vampire_bunny;
but corresponding parameters of function AddBunny are defined diffirently
BUNNY * AddBunny(BUNNY * head,int sex,int name,int colour,bool radioactive_mutant_vampire_bunny);
The abend was due to incorrect formating symbol. You defined colour as bool but trying to output it as a string literal.
printf("A new bunny is born: sex %s , name %s , colour %s , radioactive %d",head->sex,head->name,head->colour,head->radioactive_mutant_vampire_bunny);
You wrote colour %s while head->colour has type bool
By the way the address 0x00000001 shown in the message
Access violation reading location 0x00000001
is the value of colour that is equal to boolean literal true that is to 1.
Your problem is the printf statement, consider the following:
printf("Test: %s", 2);
This will produce a crash, as printf is assuming a string, but you pass an integer. The integer will thus be interpreted as char* and therefor result in an access violation as soon as printf tries to print any char (which requires dereferencing the pointer).
But this is exactly what happens if you do:
printf("A new bunny is born: sex %s", head->sex);
As BUNNY::sex is declared as int.

Constructor Error, prints out 'a' and then a triangle before crashing

QuBiEngine::QuBiEngine(ifstream& dnaFile)
{
int i = 0;
while(!dnaFile.eof()) //while the file isn't at its end
{
dna.push_back(""); //creates an element
if(!dnaFile.good())//checks for failbits and other errors
{
dna[i] = "Not a valid sequence";
i++;
continue;
}
getline(dnaFile, dna[i]);
//checks to see if the character is valid ie: a, t, c, g
for(int j=0; j<dna[i].length(); j++)
{
dna[i][j] = putchar(tolower(dna[i][j]));
if((dna[i][j]!='a')||(dna[i][j]!='t')||(dna[i][j]!='c')||(dna[i][j]!='g'))
{
dna[i] = "Not a valid sequence";
i++;
break;
}
}
i++;
}
}
This takes each line in the dnaFile ifstream and puts it in a vector if it passes the tests, if it doesn't then it just puts the not valid thing in the vector.
I figured it out, the i++ in the second if statement makes it increment twice and thus overflow my vector.
It seems that you might be missing break; in marked place:
QuBiEngine::QuBiEngine(ifstream& dnaFile)
{
int i = 0;
while(!dnaFile.eof()) //while the file isn't at its end
{
dna.push_back(""); //creates an element
if(!dnaFile.good())//checks for failbits and other errors
{
dna[i] = "Not a valid sequence";
i++;
continue;
}
getline(dnaFile, dna[i]);
bool bad = false;
//checks to see if the character is valid ie: a, t, c, g
for(int j=0; j<dna[i].length(); j++)
{
dna[i][j] = putchar(tolower(dna[i][j]));
if((dna[i][j]!='a')||(dna[i][j]!='t')||(dna[i][j]!='c')||(dna[i][j]!='g'))
{
dna[i] = "Not a valid sequence";
break;
}
}
i++;
}
}
Other than that: what is dna variable? Can you show us any declaration and initialization of it?
Other than that, if your dna is declared so that you will not get out of bounds (no checking)