-1

enter image description here

This is my code for parenthesis checker problem on geeksforgeeks. After compilling it is showing me correct answer but after submitting it is showing me segmentation fault. Please help me to resolve my problem i can't understand my mistake.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    Think about the input that starts with an closing `}`, `)` or `]`. What would `st.top()` be for an empty stack? Right it's undefined behavior. – Lukas-T Aug 29 '21 at 13:28
  • 1
    Please don't post images of text in general, and definitely not code. Copy-paste text *as text*. Also don't spam unrelated tags. Your code is C++, so don't add the C language tag. – Some programmer dude Aug 29 '21 at 13:30
  • @Someprogrammerdude that platform didn't allow me to copy the code so that's why i pasted the picture and also can you explain me the meaning of segmentation fault in c++. – Naman Verma Aug 29 '21 at 15:46
  • @churill can you provide me the exact code that works – Naman Verma Aug 29 '21 at 15:51
  • I tried recreating your issue by copying your code into my IDE. Unfortunately, my IDE can't extract code from images. No code posted as text == no help. – Thomas Matthews Aug 29 '21 at 18:37
  • And what "platform" is that? Is it some web-site that disables copying? – Some programmer dude Aug 29 '21 at 19:14
  • On another note, if it's some kind of "competition" or "online judge" site that you use to learn C++ and programming in general, then please don't do that. Such sites are not learning or teaching resources. If you want to learn invest in [some good books](https://stackoverflow.com/a/388282/440558) and go to school. And if it's a school submission site or app, then I'd argue it's not worth whatever you pay for that school, not even if it's free. – Some programmer dude Aug 29 '21 at 19:17

1 Answers1

0

You may be popping an element from the stack without having the stack filled up. Therefore, if the string does not start with {, [ or (, the program will crash.

to avoid that, check the stack has elements before popping:

//...
// line 21
else if(/* ... */ && st.size() > 0) {
st.pop();
}
// ...
midugh
  • 608
  • 5
  • 21
  • i changed the code according to you but still after submitting it's showing segmentation fault and also can you explain me the meaning of segmentation fault in c++. – Naman Verma Aug 29 '21 at 15:49
  • 2
    That size check (why not `empty()`?) needs to be the first condition to enable short-circuiting (which avoids the other conditions to be checked). – Bert Aug 29 '21 at 17:46