C++ Wierd crash on function called - c++

I checked the return of GetCharacterRankINT() and it is returning the right value (1). When I tested the query with the rankNum 1 I got the right result, but whenever I try to use GetCharacterRankSTR() it crashes with the following crash dump: http://fbe.am/rwl (Password: stackoverflow). I tried to set the type of the function from string to std::string and it still didn't work. The MySQL table has 8 columns, or so the field has 8 entries. Therefore the error is not related to the amount of fields.
string Player::GetCharacterRankSTR()
{
QueryResult* res = CharacterDatabase.Query("SELECT * FROM ars_ranks WHERE rankNum = %u LIMIT 1;", GetCharacterRankINT());
if (!res)
{
return "Error";
}
else
{
Field* fld = res->Fetch();
return fld[3].GetString();
}
}
My question is: What am I doing wrong in the function so that it crashes?

After some tests, I found out how to fix it... I just had to change from string to const char *.

Related

c_str() is only reading half of my string, why? How can I fix this? Is it a byte issue?

I am writing a client program and server program. On the server program, in order to write the result back to the client, I have to convert the string to const char* to put it in a const void* variable to use the write() function. The string itself is outputting the correct result when I checked, but when I use the c_str() function on the string, it is only outputting up until the first variable in the string. I am providing some code for reference (not sure if this is making any sense).
I have already tried all sorts of different ways to adjust the string, but nothing has worked yet.
Here are how the variables have been declared:
string final;
const void * fnlPrice;
carTable* table = new carTable[fileLength];
Here is the struct for the table:
struct carTable
{
string mm; // make and model
string hPrice; // high price
string lPrice; // low price
};
Here is a snipped of the code with the issue, starting with updating the string variable, final, with text as well as the resulting string variables:
final = "The high price for that car is $" + table[a].hPrice + "\nThe low
price for that car is $" + table[a].lPrice;;
if(found = true)
{
fnlPrice = final.c_str();
n = write(newsockfd,fnlPrice, 200);
if (n < 0)
{
error("ERROR writing to socket");
}
}
else
{
n = write(newsockfd, "That make and model is not in
the database. \n", 100);
if (n < 0)
{
error("ERROR writing to socket");
}
}
Unfortunately your code does not make any sense. And that may be your major problem. You should rewrite you code end eliminate the bugs.
Switch on all compiler warnings and eliminate the warnings.
Do not use new and pointers. Never
Do not use C-Style arrays. So, something with []. Never. Use STL containers
Always initialize all variables. Always. Even if you assign an other value in the next line
Do not use magic constants like 200 (The size of the string is final.size())
If an error happens then print the error text with strerror (or a compatible function)
Make sure that your array itself and the array values are initalized
To test your function, write to socket 1 (_write(1,fnlPrice,final.size()); 1 is equal to std::cout
There is no need to use the void pointer. You can use n = _write(newsockfd, final.c_str(), final.size()); directly
If you want a detailed answer here on SO then you need to post your compiled code. I have rewritten your function and tested it. It works for me and prints the complete string. So, there is a bug in an other part of your code that we cannot not see.

Serial.println changes return value of function (Arduino)

I've been experiencing some very odd behaviour from what should be a very simple function: an integer is passed to the function, and depending on its value will return an unsigned char specific to that integer.
I kept experiencing a problem in which it would return a different value to those that are hard coded into the function. I've had to rewrite the code a number of times to get it to stop happening, but I have found a way to recreate it every time to illustrate how something that shouldn't change the return value is doing.
Below is an example sketch to illustrate:
unsigned char* brokenFunction(int id)
{
switch (id)
{
case 0:
{
//Serial.println("Break it...");
unsigned char retval[8] = {
0b01110,
0b11011,
0b10001,
0b10001,
0b10001,
0b10001,
0b10001,
0b11111
};
return retval;
}
break;
case 5:
{
unsigned char retval[8] = {
0b01110,
0b11011,
0b11111,
0b11111,
0b11111,
0b11111,
0b11111,
0b11111
};
return retval;
}
break;
}
}
void setup()
{
Serial.begin(9600);
unsigned char* array = brokenFunction(0);
Serial.println(*array);
}
void loop()
{
}
On line 7 is a call to Serial.println which is currently commented out. If you run the sketch on your Arduino with this line commented out, the Serial.println call in the setup function will return the value 14 (which is correct).
If, however, you uncomment line 7, the Serial.println call in the setup function will now return what seems like a random value; for my last test it was the value 91; see the serial window log below:
14
Break it...
91
As you can see, my first attempt returned 14, but the subsequent attempt with the extra Serial.println call resulted in the return value being changed.
Does anyone have any idea what may be going wrong here? There were other things I did that managed to replicate this too, but this is the most simple one to use as an example. It's almost as if, if the function is taking a bit longer to finish that the return value is being corrupted some how.
Any help or ideas would be much appreciated.
You are returning a local array from the function brokenFunction(int id), which stops existing when you return, causing undefined behavior from that point on.

Access violation reading location 0x00000006

I have the following code which finds the strings that contain no Alphabets. Cases like mynumber123 shall not be recognized and the numberFinder() should return false and case like 123 shall be recognized and numberFinder() shall return true as well as the begin index of the number.
the constructor:
CaddressParser::CaddressParser(string fileName) //constructor
{
m_fileName=fileName;
int length=getLength(m_fileName.c_str());
m_text =fileReader(m_fileName.c_str());
m_length=length;
}
which initializes a string m_text that contains the contents of a text file
Somewhere along the implementation I come across the following code:
for (i;i<m_length;i++)
{
bool UpperCaseBeforeNoFound=false;
if(this->numberFinder (i).second)
{
//do some calculations.
}
}
the numberFinder function is implemented as follows:
pair <int,bool> CaddressParser::numberFinder(int counter)
{
bool noFound=isdigit(m_text[counter]); //number found? -> true
if(noFound)
{
int end=HouseNoDigits(counter);
if(((counter-1)>=0) && ((counter +end-1) <m_length))
{
if((!(isalpha(m_text[counter-1]))) && (!isalpha(m_text[counter+end-1])))
{
return make_pair(counter,noFound); //return index if true
}
}
}
else return make_pair(0,noFound);
}
Now the problem is for a text file containing the following text "he23 Market street London Q12 H13". I get the error mentioned in the headline and the debugger takes me to the line in the which contains :
if(this->numberFinder (i).second)
I can't figure out why this is happening. Please help me figure it out.
If this condition in CaddressParser::numberFinder(int counter) fails:
if (counter - 1 >= 0 && counter + end - 1 < m_length)
the function will exit without returning a value, resulting in undefined behavior.
The complexity of the conditionals in the function isn't helped by the poor formatting (at least as posted in the question).
You might get the behavior you need by removing the else so any 'fall-through' will return the default pair value (but that will depend on if that's the value you want to really return in that scenario):
pair <int,bool> CaddressParser::numberFinder(int counter)
{
bool noFound=isdigit(m_text[counter]); //number found? -> true
if(noFound)
{
// ...
}
return make_pair(0,noFound);
}
Access Violation error is normally due to NULL reference. One of the function that you are calling is trying to access a NULL pointer. Make sure your isdigit function returns true or false, m_text points to an exiting memory location. If not you need to allocate the memory. You should also check if the fileName is NULL.

C++ Error: Wunused-but-set-variable

I get the error I mentioned in the title when I try to compile the following code:
void Sql::select(const string table, const string column, const string condition, const string condition_2, const string condition_3) {
otl_stream s;
otl_column_desc* desc;
int desc_len;
const string select = str(format("SELECT %2% FROM %1% WHERE LEFT(%3%, 8) < %6% AND %4% = 'Ausstehend' AND (%5% = '1' OR %5% = '2') ")
% table % column % condition % condition_2 % condition_3 % getDate());
// cout << select;
try {
s.open(10, select.c_str(), con);
} catch (otl_exception &e) {
cerr << e.msg;
}
desc = s.describe_select(desc_len);
}
I am told that otl_column_desc* desc is set but not used. Can you tell me what goes wrong there?
Its exactly what it says, you are setting the variable but not using the value anywhere, meaning this variable is, for all intents and purposes, useless.
desc = s.describe_select(desc_len);//value in desc never used
This sometimes could happen if you make a mistake in your code, and use some other variable when you meant to use this one, and I guess this warning is to catch those cases.
But to answer your question, nothing is wrong since this is a warning, not an error. It is just an indication that something might be wrong.

c++ how to compare a string to a dynamic structure string using pointers?

I have to code a method of a class in C++ that shows me all the attributes of a class when they give me only the name. For example, I have a class 'Team' with a_name, a_goals and a_points. So when they give me a string with the name, I have to compare it to my dynamic structure and find the team with the same name to show it. I have this code:
void Classificacio::mostrar(string nom) const {
Equip eq;
Node* i=a_inici;
bool trobat=false;
while(!trobat && i!=NULL) {
if(nom.compare(i->a_equip.NomEquip())==0) trobat=true;
else i=i->seg;
}
if(trobat==true) eq=i->a_equip;
cout << eq << endl;
}
NomEquip() is a method that returns the team name.
But it doesn't work. Every time I try to execute it with the debugger, it stops in the line with the if. Any ideas what I'm doing wrong?
EDIT: Wanted to translate it to english but I forgot some things, just copy/pasted it this time.
There is a possibility of crashing in the line:
if (trobat == true) eq=i->a_equip;
Because you check for 'i!=NULLin thewhileloop. One of the terminating conditions of thewhileloop is thati == NULL`.
Assuming the while loop was terminated because i == NULL, your if statement will dereference a NULL pointer which is undefined behavior.
Edit 1:
If it crashes at if (nom.compare(i->a_equip.NomEquip()) == 0), and we know i is valid, it leads that the NomEquip function is a leading culprint.
Change your while loop to:
while (...)
{
std::string nom_equip = i->a_equip.NomEquip();
if (nom == nom_equip)
//...
}
Now place breakpoint at the std::string line and step into the function to trace it.