Items in QMap get lost [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a XML-file holding among other things some groups with name and userlists. In my code in constructor I have set a dictionary for this list:
dictGroups= QMap<QString, QList<QString>>() ;
In headerfile it is declared as
public:
QMap<QString, QList<QString>> dictGroups;
Then I read the file: ReadConfig();
void AppConfig::ReadConfig(void)
{
...
while(!reader.atEnd())
{
ReadGroups(reader);
if (dictGroups.isEmpty()) qDebug()<<"ReadConfig_isEmpty";
}
...
This is my ReadGroups:
void AppConfig::ReadGroups(QXmlStreamReader &reader)
{
dictGroups.clear();
while(!reader.atEnd())
{
reader.readNext();
if (reader.error())
{
...
}
else
{
if (reader.isStartElement())
{
if (reader.name().toString().toLower()=="group"){
ReadGroup(reader);
if (dictGroups.isEmpty()) qDebug()<<"ReadGroups_isEmpty";
}
}
else if (reader.isEndElement())
{
if (reader.name().toString().toLower() == "groups")
{
if(dictGroups.count()<=0){
QList<QString> users= QList<QString>();
users.append(this->GetUsername());
dictGroups.insert("admin", users);
}
return;
}
}
}
}
}
My problem is, that the items inserted in dictGroups while ReadGroups get lost. I get the debug output
ReadConfig_isEmpty
but in ReadGroups seems everything is ok.
I'm at a loss, puzzling around for hours, can anybody help to find the reason?

You have this code:
dictGroups.clear();
Why do you expect the dictGroups to persist when you clear them on every iteration of the outer loop? Don't do that.
The clear statement belongs perhaps at the beginning of ReadConfig.
Your method name capitalizations are very much out of place in Qt code, though: capitalized names are by convention reserved for groups.

Related

Why is "this" NULL? C++ Segmentation fault [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I'm building a Qt app and it's crashing because of a segmentation fault. After investigation, I found out that the cause of the segfault is that "this" is NULL and I try to access a member variable in the readInputFile(QString path) method.
In this line input += line;
I don't understand why this is happening. how can "this" be NULL ?
Here's where the object is created
void MainWindow::on_inpFileCheck_clicked()
{
if (ui->inpFileCheck->isChecked()) {
QString filePath = QFileDialog::getOpenFileName(this,tr("Open CSV file"), "/home", tr("CSV (*.csv)"));
myAlgo->readInputFile(filePath);
ui->inputEdit->clear();
ui->inputEdit->appendPlainText(myAlgo->getInput());
}
}
Here's the BaseAlgorithm header
#include "qstring.h"
#include "qmainwindow.h"
class BaseAlgorithm
{
public:
BaseAlgorithm();
QString readInputFile(QString);
int lenArr;
private:
QString input;
QString output;
};
And here's the implementation and where the problem happens
#include "basealgorithm.h"
#include "qfile.h"
#include "qtextstream.h"
BaseAlgorithm::BaseAlgorithm() {
numComparisons = 0;
input = "";
output = "";
intArr = NULL;
}
QString BaseAlgorithm::readInputFile(QString path) {
QFile inpFile(path);
if (inpFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream in(&inpFile);
while (!in.atEnd()) {
QString line = in.readLine();
input += line; // crash happens here
}
return input;
}
else {
return "ERROR";
}
}
In C++, it is perfectly possible to call a method via a null pointer to an object. As long as this is not actually dereferenced, the function would work fine.
UPDATE: The behavior is what is often exhibited by implementations, as this is usually treated as just another parameter in the compiled code. However, as #manni66 points out, the standard doesn't actually mandate the result of calling a method on a nullptr.
It is pretty obvious that this is NULL because myAlgo is NULL where it is called. So the question asked in the title here is answered.
Why is myAlgo NULL? We don't know because you didn't show that code.
I fixed it. The object was being created late.

How to return error code from the main function in C++? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am working on an object-oriented C++ coursework where I need to return error codes from the main function. How would one do this properly?
Unfortunately this is an assessed coursework so I cannot post my code here. But let's say the case is as follows:
I'm building an enigma machine with classes Plugboard, Reflector, and Rotor. I pass each of the configuration files as arguments in the command line. In this task, I'm provided with a file errors.h containing the following:
#define INSUFFICIENT_NUMBER_OF_PARAMETERS 1
#define INVALID_INPUT_CHARACTER 2
#define INVALID_INDEX 3
// and so on...
So I have in my program several functions to check the errors, for example a function to check whether the configuration file contains an invalid character (it has to be 0 to 25). I was thinking of setting this as a boolean function and then in my main function have the following:
if (!plugboard.check_invalid_character(/*some arguments*/)) {
cerr << "Invalid character!" << endl;
return 2;
}
But I'm not completely sure this is the right way to do it? Is it too superficial? Is there a more elegant way of returning error?
I hope my question is a little clearer this time. Thanks before.
You just need to return the value 4 in your main method like this:
int main() {
return 4;
}
Please note that your main function could also have the arguments vector and the argument count so there could be more in the brackets.
If KLibby is right and you use a method with returns the value you need to use something like that:
int doSomething() {
return 4;
}
int main() {
return doSomething();
}

Escaping from commented out block [duplicate]

This question already has answers here:
Nested Comments in C++
(4 answers)
Closed 9 years ago.
While this problem can apply to other languages I am looking for solutions that can apply to C++ language.
The problem is, when we comment a block like:
void doStuff() {
cout<<"doing stuff";
/*start();
cout<<"done";*/
}
The comment out works completely fine, however what I am wondering is when I want to comment out entire function by:
/*void doStuff() {
cout<<"doing stuff";
/*start();
cout<<"done";*/
}*/
It obviously doesn't work. The only way that I know to make it work is either:
/*void doStuff() {
cout<<"doing stuff";
start();
cout<<"done";
}*/
OR
/*void doStuff() {
cout<<"doing stuff";
*//*start();
cout<<"done";*//*
}*/
I know that there are IDE's that can automatically insert // at each line and then get rid off it but that's not what I am after.
My question is, is there any easier way of escaping from inner commented out blocks?
You can't do it with comment grammer.
Use #if 0 #endif to comment out a large portion of code with /* */ inside.

Removing a node from the middle of a linked list [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am using the following code on a linked list of characters. But whenever I run this program, I get a runtime error.
void ldellist(Node *head,char k)
{
Node *remove=head;
Node *previous=head;
while(remove->data!=k)
{
remove=remove->next;
}
while(previous->next!=remove)
{
previous=previous->next;
}
previous->next=remove->next;
free(remove);
}
Could someone tell me what's the problem?
Perhaps you need to do some checks?
void ldellist(Node *head,char k) {
Node *remove=head;
Node *previous=head;
while(remove && remove->data!=k) {
remove=remove->next; }
while(previous && previous->next!=remove) {
previous=previous->next; }
if (remove) {
previous->next=remove->next;
free(remove);
} else {
// print some error like 'not found'
}
}
In the case when the node to remove is head, you'll get "remove" equals "head" and condition "previous->next!=remove" will be always true.

Under what circumstances is it feasible to use exception handling? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have seen many exception handling mechanisms where they simply weren't necessary. A lot of the times the problem could have been solved in a much cleaner way using simple if statements.
For example, things like:
Invalid input
Division by zero
Wrong type
Container range check
Null pointer
Uninitialized data
... and so on.
Could someone provide an example where it would be a better approach to handle exceptions?
Exceptions become more important as your program size grows.
With a simple application return codes are probably fine. But when an error condition needs to bubble up a couple levels of the stack before being handled, it starts to make sense to use exceptions instead of passing error codes from every function.
Also, when a method already returns a value, it may not be practical or possible to return an error code from the function as well.
Sometimes using exception is cleaner. In function foo thanks to exception throwing in check function you can avoid checking what check returns what makes this function simpler:
#include<iostream>
using namespace std;
class A{
public:
int a_foo(int index){return _tab[index];}
private:
static int _tab[3];
};
int A::_tab[3]={1,2,3};
void check(int index)
{
if (index < 0 || index > 2)
throw string("invalid index");
}
void foo(A a, int index){
check(index);
cout << a.a_foo(index) << endl;
}
int main()
{
try
{
A a;
foo(a,4);
}
catch(string ex)
{
cerr << ex <<'\n';
}
}
I would use it when the consequence of some unexpected 'event' is inability for application to continue running. When it happens and you catch it, report it nicely and close the application (or whatever you think you should do in that case).