Reputation: 31
I am getting std::logic_error: basic_string::_s_construct null not valid
in this program. How can I solve that? I already tried a previously posted solution but could not correct it myself.
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
stack<string> s;
string temp, exp[] = "abc-+de-fg-h+/*";
string ch1 = 0, ch2 = 0, ch = 0;
int sizeExp = sizeof(exp)/sizeof(*exp);
for(int i=0; i < sizeExp ; i++) {
ch = exp[i];
if (ch == "*" || ch == "/" || ch == "+" || ch == "-") {
if (s.empty() && sizeof(temp) != sizeof(exp)) {
cout << "Error in Expression." << endl;
}
else {
if (sizeof(s.top()) != sizeof(char)){
ch1 = s.top();
s.pop();
ch2 = s.top();
temp = '(' + ch2 + ')' + exp[i] + '(' + ch1 + ')';
s.push(temp);
}
else {
ch1 = s.top();
s.pop();
ch2 = s.top();
temp = ch2 + exp[i] + ch1;
s.push(temp);
}
}
}
else {
s.push(exp[i]);
}
}
cout << temp << endl << "Is your Infix Expression for ";
cout << exp;
return 0;
}
Upvotes: 2
Views: 18862
Reputation: 385154
The documentation for std::string
clearly states that you shall not construct one from a null pointer. Yet, here you are, doing just that!
string ch1 = 0, ch2 = 0, ch = 0; // BAD
string ch1, ch2, c; // Substantially better
Upvotes: 3
Reputation: 16737
The issue is with statements of the sort std::string str = 0;
. This leads to undefined behaviour. Use std::string str = "";
to create empty strings.
std::string str = 0;
resolves to the constructor std::string::string(const char* s, const Allocator& alloc = Allocator())
. The behaviour of this constructor is undefined when s
is nullptr
. Your argument of 0
gets converted to nullptr
.
Upvotes: 8