C++ Logo

std-discussion

Advanced search

Re: Segmentation Fault with stack top access.

From: Hans Åberg <haberg-1_at_[hidden]>
Date: Mon, 11 Oct 2021 20:59:55 +0200
> On 11 Oct 2021, at 19:58, Gennaro Prota via Std-Discussion <std-discussion_at_[hidden]> wrote:
>
>> On Mon, Oct 11, 2021, 08:54 Anubhav Guleria via Std-Discussion <std-discussion_at_[hidden]> wrote:
>> Thanks for clarifying.
>>
>> Any specific reason why container's pop_back method can't check for
>> current size and if it is 0 then make the pop operation a no-op?
>>
> You'll find that C and C++ people are, with very few exceptions, fixated with micro-optimizations (a known anti-pattern). I think that, if they built cars, they wouldn't install any brakes, because they would think the weight of them would slow down the car. You might have heard of the "don't pay for what you don't use" principle. That's a fraud they are fond of: it's a fraud because it only concerns runtime speed, but then often leads to dangerousness which has an impact on the reliability of your programs, or to crazy complexity, so you are actually paying for speed or complexity that you don't need.
>
> That being said (this is my genuine opinion, and I'm not interested in a heated discussion), popping from an empty stack is a programming error and the behavior you propose would hide it. What is needed in this case is an assertion, which, actually, might be provided by your library in debug mode. (You should leave assertions enabled in your release builds, unless the profiler shows that it is necessary to turn them off.)

You probably have to check whether the stack is empty before popping it. So it is a difference between styles, assuming that the class checks and throws an exception:
  if (stack.empty()) {
    …
  }
  else {
    stack.pop();
  }
and
  try {
    stack.pop();
  } catch (stack_empty&) {
    …
  }

Received on 2021-10-11 14:00:04