Control reaches at the end of non-void function [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 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?

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.

C++ Queue error [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 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.

Why wouldn't the head change - linkedlist implementation [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 8 years ago.
Improve this question
What I'm trying to do is to insert a node with a value to the ith location of a linked list. It has to return true if the insertion was successful, false otherwise. What I'm not able to understand is how to add to the start of the list. What I tries did not insert it at all. Where is the problem?
bool insertat(struct Node*head, int value,int loc){
Node *q = new Node;
q->data=value;
if(loc>list_length(head)){
insertlast(head,value);
return true;
}
else if(loc<=0){
cout<<"invalid location";
return false;
}
else if(loc==1){
q->next=head;
head=q;
return true;
}
else{
int i=1;
Node*p =head;
while( i<loc-1){
p=p->next;
i++;
}
q->next=p->next;
p->next=q;
return true;
}
}
This is because you are passing pointer by value. So, changes done to head in this function are lost.
Rather change your function to:-
bool insertat(struct Node**head, int value,int loc)
and pass the address of head.
OR
bool insertat(struct Node*&head, int value,int loc)

Segmentation fault on list in C++ [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 8 years ago.
Improve this question
I'm using a class which holds a private list:
class Set
{
private:
list<long long unsigned> ways; //holds tags of addresses
and as part of the class's functionality I'm managing a LIFO on the list 'ways':
list<long long unsigned>::iterator it = ways.begin();
while (it!= ways.end()) //looks for the tag in the list
{
if ((*it) == tag) //tag is found in this set. moves the tag to the end of the list
{
ways.erase(it);
ways.push_back(tag);
return true;
}
it++;
}
return false;
and:
if (occupied < maxWays) //if the set is not all used up just pushes tag in the end
{
ways.push_back(tag);
occupied++;
return false;
}
else // if used up pops the front member (the least recently used one)
{
ways.pop_front();
ways.push_back(tag);
}
return true;
Nothing else touches 'ways' and nothing else erases the class 'set'.
Multiple instances of the class 'set' are created at the beginning.
During operation I'm getting Segmentation Fault for
list<long long unsigned>::iterator it = ways.begin();
which occurs after a long run. Trying to print the address of 'ways' before this line shows that at the point that I'm about to get Segmentation Fault the address of 'ways' changed dramatically.
All the previous times it was around 0x6000xxxxx for each instance, and at that time it was 0x23.
I don't have a clue what can cause that, please assist.
It might be that you delete an element from the list, and then increment the iterator, which points to the deleted element.
You probably need to forward the iterator first, and then remove the previous, to achieve what you want.
See:
Can you remove elements from a std::list while iterating through it?
EDIT: See also the return value of erase(), and similar operations that modify the iterator bag.
http://www.cplusplus.com/reference/list/list/erase/
Are you initiliazing 'occupied' and 'maxWays' ? If not, see example where it fails as we are calling ways.pop_front() on empty list ways
class Set
{
public:
Set(int max)
{
maxWays = max;
occupied = 10; // Say randomly stored value 10 is more than maxWays = 5
}
bool search(long long tag)
{
list<long long unsigned>::iterator it = ways.begin();
while (it!= ways.end()) {
if ((*it) == tag) {
ways.erase(it);
ways.push_back(tag);
return true;
}
it++;
}
return false;
}
bool add(long long tag)
{
if (occupied < maxWays) {
ways.push_back(tag);
occupied++;
return false;
}
else {
ways.pop_front(); // may fail here
ways.push_back(tag);
}
return true;
}
private:
list<long long unsigned> ways;
int maxWays;
int occupied;
};
int main()
{
Set set(5);
cout << set.add(100) << endl;
return 0;
}

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
}