Reputation: 1
I have tried to execute this code but it keeps throwing this error. could you help me fix it?
"Line 1034: Char 9: runtime error: reference binding to null pointer of type 'char' (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:9"
vector<char> parenth;
int top = -1;
//pushing
if(top == -1){
top++;
parenth[top]= x;
}else{
top++;
parenth[top] = x;
//popping
switch (x){
case ')' :
if(parenth[top-1] == '('){
top -=2;
}
case '}' :
if(parenth[top-1] == '{'){
top -=2;
}
case ']' :
if(parenth[top-1] == '['){
top -=2;
}
}
}
Upvotes: 0
Views: 892
Reputation: 1
The problem is that you've created an empty vector and then trying to access that empty vector's elements leading to undefined behavior.
To solve this you can make the vector to be of a particular size at the time of its creation and then use std::vector::at
so that an exception is thrown if we accidentally go out of bounds of the vector and so there is no more UB.
//--------------------v--------->pass the size that you want your vector to have
vector<char> parenth( 5 );
//some code here
//------vv----------------------->use std::vector::at so that if we mistakenly go out of bounds the exception is thrown and we don't get UB
parenth.at(top) = x;
Upvotes: 1