Passed string become empty in gdb? - c++

I have the following code:
CrowdSim::Simulation my_simulation;
void printstring(std::string filename)
{
std::cerr<<"filename= " <<filename<<std::endl;
}
int main(int argc, char* argv[])
{
std::vector<std::string> tokens;
std::string filename = "";
if(argc > 1)
{
std::string args(argv[1]);
split(tokens, args, is_any_of("\"="), token_compress_on);
filename = tokens.at(1);
}
my_simulation = CrowdSim::Simulation();
printstring(filename);
I run the program with the following
./CrowdSim -filename="Layout/layout_1"
Within gdb, I put a breakpoint right before printstring(filename). When hitting this breakpoint, I execute print filename, and the output is "Layout/layout_1". Immediately after entering printstring (stepping in with step), I print filename and the result is "".
However, if I actually let the next line run, the output is fine: it prints filename= Layout/layout_1. Is this some sort of gdb error? It's making it very hard to debug without using a ton of cerr statements. What could be causing this?
Additionally, if I comment out all lines involving my_simulation (so that it never gets initialized and I never use it) I get an error upon stepping into printstring:
printstring (filename=Traceback (most recent call last):
File "/usr/share/gdb/python/libstdcxx/v6/printers.py", line 469, in to_string
return self.val['_M_dataplus']['_M_p'].string (encoding, length = len)
RuntimeError: Error reading string from inferior: Input/output error
) at Source/main.cc:13
I also tested this with a program which contains only the above main and printstring functions, with no references to any other objects. The above error still occurs.
Can anyone explain either of these errors to me? Also, somewhat related, in c++, does the line CrowdSim::Simulation my_simulationautomatically call the constructor, so that I no longer need the line my_simulation = ...? In Java, declaring a variable doesn't construct it (as far as I know), so both lines are usually necessary (I think).

Related

C++/Tcl Can I retrieve Tcl file line number when a function recorded by Tcl_CreateCommand is invoked

I run a Tcl script from a C++ program using Tcl_EvalFile. I defined some custom commands (using Tcl_CreateCommand), so when they are found in the file a callback is called and then I can run some C++ code (TclInvokeStringCommand invokes the callback given to Tcl_CreateCommand, the callback type is int (*executeCmd)( ClientData data, Tcl_Interp *interp, int argc, const char *argv[] )).
I want to know the script file name and line number within the callback function being invoked.
I could get the script file name using ((Interp*) interp)->scriptFile.
However, I could not get the script file line number. Is there a way to retrieve this (or compute it in any way)?
The information is only exposed at the Tcl level via the info frame command. (The internal C API for it is sufficiently horrible that it's never been made public.) This means you need to do something like this with Tcl_Eval():
// These can be cached safely per thread; reference management is a thing for another question
Tcl_Obj *scriptNameHandle = Tcl_NewStringObj("file", -1);
Tcl_Obj *lineNumberHandle = Tcl_NewStringObj("line", -1);
// How to actually get the information; I'm omitting error handling
Tcl_Eval(interp, "info frame -1");
Tcl_Obj *frameDict = Tcl_GetObjResult(interp);
Tcl_Obj *scriptNameObj = nullptr, *lineNumberObj = nullptr;
Tcl_DictObjGet(nullptr, frameDict, scriptNameHandle, &scriptNameObj);
Tcl_DictObjGet(nullptr, frameDict, lineNumberHandle, &lineNumberObj);
// Now we have to unbox the information
if (scriptNameObj != nullptr) {
const char *filename = Tcl_GetString(scriptNameObj);
// Do something with this info; COPY IT if you want to keep past the result reset
}
if (lineNumberObj != nullptr) {
int lineNumber = -1;
Tcl_GetIntFromObj(nullptr, lineNumberObj, &lineNumber);
// Do something with this info
}
// Release the result memory, i.e., the dictionary and its contents
Tcl_ResetResult(interp);
Note that neither the file nor the line keys are guaranteed to be present; the line key is usually there, but the file key is only there when running code that can be tracked back to a file, i.e., back to Tcl_EvalFile() and related.

ofstream returning error "No matching function to call std::basic_ofstream<char>::close(const char [14])"

Need help fixing my code, not sure what's wrong. I'm using C++11, trying to write a vector to a file by individually writing each struct. The section of code returning an error is:
string craigSave = "craigSave.txt";
ofstream file(craigSave.c_str());
file.open("craigSave.txt");
for (int i=0; i<finalVector.size(); i++){
file << finalVector[i]<<endl;
}
file.close("craigSave.txt");
cout<<"Thanks for shopping!"<<endl;
done = true;
The error returned is on the "file.close" line and is:
error: no matching function for call to 'std::basic_ofstream::close(const char [14])'
I research on this error seems to point to needing to use char* as an argument instead of a string, but I'm using C++11, so it should accept strings. Also it is strange that there is no error for the file.open line, as all research shows the error being there, not at file.close
Just use file.close();, there's no need to pass the file name again.
See http://www.cplusplus.com/reference/fstream/ofstream/close/.
Also, ofstreams are RAII objects, which means that the file will automatically be closed once the ofstream object goes out of scope (see do I need to close a std::fstream?):
{
ofstream out("name");
// do something with out...
} // out.close is called automatically

How to use a variable in the same struct it's defined in?

I am making a rogue-like ASCII game and made a struct called "Armor" and I want to use the name variable in the struct to have the path to whatever the name is.
struct Armor {
bool equipped;
std::string name;
int getBuff(int buff) {
std::fstream item;
std::string line;
std::string response;
std::string value;
item.open("../Data/Items/" + name + ".item", std::fstream::in);
if (item.fail())
errorQuit("ERROR: There was a problem loading armor type .ITEM file."); // Error and quit function
while (!item.eof()) {
getline(item, line);
response = split(line, '=', 0); // Splits string
if (response == "buff" + std::to_string(buff)) {
value = split(line, '=', 1);
break;
}
}
item.close();
return std::stoi(value);
}
};
Then I called it like this:
Armor sword;
sword.name = "Wooden Sword";
int buff = sword.getBuff(1);
But this throws an Unhandled exception error.
I changed it so that getBuff takes 2 parameters, int buff and std::string itemName. and replaced name in the path with itemName;
Then I tried calling it like this:
Armor sword;
sword.name = "Wooden Sword";
int buff = sword.getBuff(1, sword.name);
But this throws the same error.
I'm confused as to why I can't use the name variable as it has already be defined. Is there any other way I can use the name variable like that?
I see you've just edited your comment to say you've figured your problem out, but I just want to add something else that may be helpful:
Without seeing how errorQuit() is defined, there's a potential problem in your getBuff() function. If the expression if (item.fail()) evaluates to true, the function may continue on trying to process the data (unless errorQuit() somehow breaks out of the program or something, which probably isn't the best approach).
Basically, testing for fail() may or may not provide the behavior you require in all scenarios, depending on what bits are set in the stream state. Implementations vary, but... if the file fails to open, failbit and/or badbit will be set, but not eofbit. getline() will see the error state and so it will not try to read from the stream when you call it. But that also means the eofbit will never be set!
There's lots of different "techniques" to file reading. Some people prefer an RAII approach. Others like looping on getline(). Or you could even just use good() to check the error state if you don't care what happened and simply want to know if everything is fine or not.
In any case, you might be interested in the info on this page: std::ios_base::iostate.
Thanks for all your help but I figured it out on my own.
I just made a stupid error that I overlooked like an idiot.
It is searching for buff + int (e.x. buff1) in the file but there are multiple lines that contain that word so I guessed that messed it up. I just made an adjustment to the if statement and it is working as expected.
Sorry to bother you!
your getBuf() function fails on some io-operation and throws an exception.You dont handle exceptions and thus the application quits with the appropriate message. Try surrounding the call to getBuf with try/catch (add the includes to iostream and stdexcept)
try {
int buff = sword.getBuff(1);
}
catch (const std::exception &e) {
std::cout << e.what() << std::endl;
}

Segmentation fault when calling fread() c++

I dont understand the mistake I am making.
I tryed alot but I am unable to read my FILE.
Basically I write an structure into a file named 0.txt / 1.txt / 2.txt ... based of account amound.
I realy seached hours to fix my problem but I dont understand how I can fix and why I get the ERROR.
Also I have no problem in complining my code (with dev c++) but when I press on Load Accounts Button I get the ERROR "Segmentation Fault" (using windows 7).
I noticed that the problem is at fread() line in function ladeAccounts().
The name of my Structure is "iAccount".
The variable infoma is as iAccount typed and the "number of accounts existing" typed as int anzahl in newAccount() decides the path.
iAccount looks like this:
struct iAccount
{
string ID;
string password;
int level;
};
This is how I write my STRUCT into the FILE:
void Account::newAccount(int anzahl, string username, string pw, int lvl)
{
iAccount neu;
neu.ID = username;
neu.password = pw;
neu.level = lvl;
ss.str("");
ss<<anzahl;
s = ss.str();
s = "Accounts/"+s+".txt";
f1 = fopen(s.c_str(), "w");
fseek(f1, 0, SEEK_SET);
fwrite(&infoma, sizeof(iAccount), 1, f1);
fclose(f1);
}
This is how I read the File (ERROR APPEARS when I call fread()
void Account::ladeAccount(int nummer)
{
stringstream sa;
iAccount account_geladen;
sa.str("");
sa<<nummer;
s = sa.str();
s = "Accounts/"+s+".txt";
f2 = fopen(s.c_str(), "r");
fseek(f2, 0, SEEK_SET);
fread(&infoma, sizeof(infoma), 1, f2);
fclose(f2);
}
Thank you for your help. I have no clue where my problem is and as I said I am searching for hours.
EDIT:
The file gets opened I tryed it (f2 is true!).
EDIT":
ERRNO = 0 !!!
SEE HERE:
ostringstream Str;
Str << errno;
infoma.ID = Str.str();
Just did this to see the result of errno in my wxtextlabel.
Reason
You are most probably calling fread on a NULL file handle. So you have two problems here:
In your code (you don't check if fread succeeds or returns a NULL value)
Your file can't be opened for some reason (this, you should investigate...)
Explication
fopen (see documentation) can return a NULL handle for different reasons. If you don't check the validity of the handle before calling fread you will have a segmentation fault.
Tips
As you can read in the official documentation I linked above, on most library implementations the errno variable can help you giving the system-specific error code on failure. This could help you debugging your error in opening the file.
Side Issues
Once you solve this bug in our code you will have other issues. As people (notably #Christophe) remarked in other answers, there is a structural problem in your code because you try to serialize/deserialize on your file objects non POD (aka your strings). Since string are complex objects you can't serialize them directly.
The approach of using an array of characters will work correctly, as simple types can be handled the way you coded.
For this reason, you can use the std::string c_str() method to obtain a null terminated array of chars from your string and store it in the file.
The opposite operation is even more straightforward, as you can initialize a std::string simply passing the deserialized array of chars:
std::string str(the_array);
You have a problem because you use fread() to load binary data. But this works only with plain old data (POD) objects.
It uses to give desastrous results with less trivial objects especially if the internals of these manage dynamic memory allocaton and/or pointers like it's the case here with strings.
By the way:
If you read/write binary data, you should really use "rb"/"wb" as mode for fopen(). If you don't you would'nt necessary have a seg.fault, but your data might be incorrect on some systems.
Edit:
Sorry, I didn't read well enough: if it happens right at fread() the reason provided by Alex will certainly help. However I leave this answer because as soon as you've solved your fopen() issue, you might get segmentation errors if you try to work with the object that you've read. If you're not conviced, look at sizeof(iAccount) and compare it to the size your string content.
EDIT
if(f2) is true so I am wrong and file got opened successfull right?
I found out that the file is not opened/the fopen can not handle with the path for example 0.txt .
Also I tryed to enter the path directly without building it (without stringstream and so on). Still I have the problem of the segmentation fault. I checked everything the file exists in the folder Accounts. I have an other file called "Accounts.txt" in the same folder and there I have no problem reading the amound of accounts existing (also using a struct). There I dont even check if the fopen had success but it works anyway I will write the code for the file-open-check later.
The code for the reading/writing into Accounts/Accounts.txt is:
struct init{
int anzahl_1;};
init anzahl;
FILE* f;
static string ss = "Accounts/Accounts.txt";
int account_anzahl1()
{
f = fopen(ss.c_str(), "r");
fread(&anzahl, sizeof(init), 1, f);
fseek(f, 0, SEEK_END);
fclose(f);
return anzahl.anzahl_1;
}
void account_anzahl_plus()
{
anzahl.anzahl_1 = anzahl.anzahl_1 +1;
f = fopen(ss.c_str(), "w");
fwrite(&anzahl, sizeof(init), 1, f);
fclose(f);
}
There I have no problem!

how to get error line number in C++ program

I want to handle errors in my c++ program, so I created some exception classes to manage those errors, but I want to specify at which line in my program the error occurred.
I passed LINE macro to the constructor of my exception class.
For example:
void f(int i){ // LINE A
if(i<0)
throw(OutOfRange("message", __LINE__); // LINE B
}
void main(){
try{
f(-6); // LINE C
}
catch(const OutOfRange& error){
//do something
}
}
In this example I can only get the LINE B number, but I want to get LINE A and LINE C numbers.
Any idea, where and how to use LINE macro ??
Thanks.
You are looking for a stack trace and there's no portable way to get it. Something somewhat similar can be achieved with:
struct SourcePoint
{
const char *filename;
int line;
SourcePoint(const char *filename, int line)
: filename(filename), line(line)
{ }
};
std::vector<SourcePoint> callstack;
struct SourcePointMarker
{
SourcePointMarker(const char *filename, int line)
{
callstack.push_back(SourcePoint(filename, line);
}
~SourcePointMarker()
{
callstack.pop_back();
}
}
#define MARK_FUNCTION \
SourcePointMarker sourcepointmarker(__FILE__, __LINE__);
Then right after the beginning of each function (or point of interest) you just add a line... for example
int myFunction(int x)
{
MARK_FUNCTION
...
}
Using this approach in your error handlers you can know who was called by who and so on (of course you will know only functions or places that have been instrumented with MARK_FUNCTION). If this is needed only during testing (and not in production) then probably you should just enable core dumps and learn how to run a debugger in post-mortem analysis.
You need a stack trace and a debugger. There's no way in Standard C++ that you could find line C without passing it in as an argument (f(-6, __LINE__)), and no way at all that you could find Line A.
Line C would be near impossible (I can't think of a way... except by passing a second argument to f, __LINE__.
Line A as follows:
void f(int i){ const int lineA = __LINE__;
if(i<0)
throw(OutOfRange("message", __LINE__); // LINE B
}
The CPPUNit framework uses macros instead of functions. That way you can easily get the line number at the same place where the macro is called.
I don't think it is a valid approach in a general sense, but you may find it interesting to take a look at the way the CPPUnit developers did it.
In addition to __LINE__, you can also use __func__ and __FILE__ to give you more information.
__func__ will give you line A and you can at least get a line inside the catch-block by rethrowing from there, but I don't know another way to get line C.
It would probably help you to create a backtrace using standard C++11, i.e. cross-platform and without the need for a debugger or cumbersome logging.
In the years since this question was asked, some useful features have been added to C++.
You can trace the call stack that led to an exception using:
std::nested_exception and std::throw_with_nested
It is described on StackOverflow here and here
This will, however, require that you insert try/catch statements at the functions you wish to trace (i.e. functions without this will not appear in your trace).
You could automate this with macros, reducing the amount of code you have to write/change.
Since you can do this with any derived exception class, you can add a lot of information to such a backtrace!
You may also take a look at my MWE on GitHub, where a backtrace would look something like this:
Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"