C++ Queue error [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
This is my Queue declaration here
// TODO: Declare a queue here - e.g. as a global variable
queue<string>myQueue;
This here is where I think my problem is. Whenever I run the program, I get an error stating "deque iterator not dereferencable."
string receiveMessage()
{
string messageValue = noMessage; // Don't change this value unless there is a message - default is improtant
messageQueueMutex.lock();
try
{
// TODO: Set hasMessages to true if your queue is not empty, otherwise set it to false:
if(!myQueue.empty())
{
bool hasMessages = true;
}
else
{
bool hasMessages = false;
}
// TODO: Remove the first message from your queue and place it in messageValue:
messageValue = myQueue.front();
myQueue.pop();
}
catch (...)
{
cout << "Exception occurred - check your code!" << endl;
}
messageQueueMutex.unlock();
return messageValue;
}

You don't need to use unlock() here, std::mutex will automatically unlock when it goes out of scope. Also, hasMessages will not be accessible after the if-else statement b/c it is declared inside the scopes of the if-else statement. So, you need to do:
bool hasMessages;
if(!myQueue.empty())
{
hasMessages = true;
}
else
{
hasMessages = false;
}

If the queue is empty, this code will still attempt to remove the first element from the queue. If you don't believe me, just ask your rubber duck.
This is, of course, undefined behavior.

Related

Parenthesis Checker gfgs [closed]

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 1 year ago.
Improve this question
The following code is giving segmentation fault can anyone tell why. this is a geeks for geeks practice problem (Parenthesis Checker) .
Q- Given an expression string x. Examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp.
For example, the function should return 'true' for exp = “[()]{}{()()}” and 'false' for exp = “[(])”.
bool check(string s)
{
stack<char> save;
int x = s.size();
for(int i=0;i<x;i++)
{
if(s[i]=='{' || s[i]=='['|| s[i]=='(')
{
save.push(s[i]);
}
else if(s[i]=='}'){
if(save.top()=='{')
{
save.pop();
}
else{
return false;
}
}
else if(s[i]==']')
{
if(save.top()=='[')
{
save.pop();
}
else{
return false;
}
}
else if(s[i]==')')
{
if(save.top()=='(')
{
save.pop();
}
else{
return false;
}
}
}
if(!save.empty())
{
return false;
}
else{
return true;
}
}
You have a chance to seg-fault when the stack is empty and the next character in the string is a closing paren.
E.g. if the input string is ")" or "())" your program will not behave as intended.
You will need to change the if statements from
if (save.top() == '('){...} to if (!save.empty() && save.top() == '('){...}
And similarly for every other case where you check save.top (The preceeding code does not guarantee that the stack is not empty at that given point).
Note: You would also need to do this for each occurrence of pop as well, but the guards before top() will guarantee that the stack is not empty when you then pop.

Both if and else part are executing [closed]

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 5 years ago.
Improve this question
/*Q_INVOKABLE*/ void LinkDestUI::selectDeselectSingleDestination(int iXmlId)
{
for(const auto &subNode : m_nodeColl)
{
if(bMultipleSelect())
{
if(subNode->getXmlId() == iXmlId)
{
LOG(Severity_Error)<<"1 ";
subNode->setbSelected(!subNode->bSelected());
}
}
else
{
if(subNode->getXmlId() == iXmlId)
{
LOG(Severity_Error)<<"2 ";
subNode->setbSelected(!subNode->bSelected());
}
else
{
LOG(Severity_Error)<<"3 ";
subNode->setbSelected(false);
}
}
}
}
When i execute my code then compiler goes to else part and exceute both if and else statement inside the else part. why?
That seems ... (temporarily increasing my tactfulness attribute so as to avoid offending) ... rather unlikely :-)
It's probably because the code is being entered more than once and you're just assuming it's executing both parts because of the output.
My advice would be to change the code in the outer else to be:
LOG(Severity_Error)<<"Starting inner if ";
if(subNode->getXmlId() == iXmlId)
{
LOG(Severity_Error)<<"2 ";
subNode->setbSelected(!subNode->bSelected());
}
else
{
LOG(Severity_Error)<<"3 ";
subNode->setbSelected(false);
}
LOG(Severity_Error)<<"Ending inner if ";
You should not see both blocks executing without an intervening end/start message set.

Set function in c++ not working [closed]

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 7 years ago.
Improve this question
Im writing a Set class in c++(i know there is already a library this is an assignment) and similar to the one in C++ im writing a function to check if the entry being inputted is already in the set
void Set::insert(const Set::value_type& entry)
{
for (int i=0; i<used;i++)
{
if(data[i]!=entry && used<CAPACITY)
{
data[used] = entry;
used++;
}
else
{
throw "Out of capacity in Set and Intger already in Set";
}
}
}
What the function does is look if the number is in the set. If the number is not in the set and if used < capacity (meaning their is still room) then the number is inserted. When i use the insert function nothing happens. Could someone help me out. Maybe im approaching this the wrong way.
As written, when insert-ing to an empty Set, used will be 0, so the loop terminates without doing anything. You don't handle the case where the value wasn't found after the loop, so it never inserts.
Even if you switched to loop to CAPACITY, the inner check is going to fill the whole Set with the same value on first run (because the if check's block executes, but doesn't break the loop, so it stores the same value over and over until it fills the Set or finds itself), then on subsequent inserts, it will immediately raise an exception for being full. Perhaps you wanted something like this?
void Set::insert(const Set::value_type& entry)
{
// If you have a membership test function, you can reuse it here instead
// of including this loop, e.g.:
// if (this->contains(entry)) return;
for (int i=0; i < used;i++)
{
if (data[i] == entry) {
// value already in set, nothing to do
return;
}
}
// Not already in Set, add if we have room or raise exception
if (used < CAPACITY) {
data[used++] = entry;
return;
}
throw "Out of capacity in Set";
}
When the set is initially empty, so that used == 0, your loop doesn't do anything, because the i < used condition fails immediately. So you never add the new item to the set.
And if there are items in the set, the loop adds the new entry to the set if it's different from any existing element. It adds it repeatedly for each element that it's not equal to.
What you need to do is go through the entire set, and see if a match is found anywhere. If it makes it through the entire loop without finding a match, it adds the new entry.
void Set::insert(const Set::value_type& entry)
{
for (int i=0; i<used;i++)
{
if(data[i] ==entry)
{
return;
}
}
// Not found, add it
if (used < CAPACITY) {
data[used++] = entry;
} else
{
throw "Out of capacity in Set";
}
}

Control reaches at the end of non-void function [closed]

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 7 years ago.
Improve this question
I am doing a question on Hackerrank ,but whenever I compile my code it shows control reaches at the end of non-void function .Here is my source code :
/*
Compare two linked lists A and B
Return 1 if they are identical and 0 if they are not.
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
int CompareLists(Node *headA, Node* headB)
{
if(headA==NULL&&headB==NULL)
{
return 1;
}
else if( headA!=NULL&&headB!=NULL)
{
while(headA!=NULL&&headB!=NULL)
{
if(headA->data==headB->data)
{
headA=headA->next;
headB=headB->next;
}
else
{
return 0;
exit (0);
}
return 1;
}
}
else
{
return 0;
}
}
Please tell how to rectify this and thanks in advance.
I can see two problems with reachability here. First the simple one:
{
return 0;
exit (0);
}
The exit call is unreachable. (That line is almost certainly a mistake. I can't think of any good reason to call exit there.)
Next the more complicated one ... that is the root cause of the compilation error:
while(headA!=NULL&&headB!=NULL)
{
if(headA->data==headB->data)
{
headA=headA->next;
headB=headB->next;
}
else
{
return 0;
exit (0);
}
return 1;
}
Look at where the return 1; is. It is INSIDE the loop.
So, what happens if headA != NULL && headB != NULL evaluates to false? In that case, the loop body with the return 1; at the end is skipped ... and you reach the end of the method.
Hence the compilation error.
I suspect that the "fix" is to move the return to after the loop, but I didn't try to understand the logic of your code, so that might be the wrong "fix".
What happens after this code executes?
if(headA->data==headB->data)
{
headA=headA->next;
headB=headB->next;
}
...if headA->next == NULL or headB->next == NULL?

return statement not returning values [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
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
Improve this question
emp* emp::check(string a,emp* ceo)
{
emp* l;
employee* b;
l=ceo;
if(l->name==a)
{
cout<<l->name;
return l;
}
b=l->j;
while (b!=NULL)
{
check(a,b->junior);
b=b->next;
}
}
void main()
{
l = check(d,ceo);
cout<<l->name;
}
now initially the value of l->name is being printed but finally in main value of l is not being returned.
this means that it is reaching the return statement but l is not being returned.
can someone explain why?
What is happening is this, it is matching in one of the recursive calls to check and you then discard the return value. You need to change the function to look like this:
emp* emp::check(string a,emp* ceo)
{
emp* l;
employee* b;
l=ceo;
if(l->name==a)
{
cout<<l->name;
return l;
}
b=l->j;
while (b!=NULL)
{
l = check(a,b->junior); // <----- line changed
if (l)
return l; // If we found something, return it.
b=b->next;
}
return 0; // <----- Always return a value
}
Also, there are various stylistic issues with your code, it would be clearer if you made changes something like this so that your variable and function names are useful:
emp* emp::findEmployeeByName(string name,emp* root)
{
if(root->name==a)
{
cout<<root->name;
return root;
}
// What on earth is ->j? Give your members meaningful names
for (employee* worker=l->j; worker; worker = worker->next)
{
emp* match = findEmployeeByName(name,worker->junior); // <----- line changed
if (match)
return match; // If we found something, return it.
}
return 0; // <----- Always return a value
}