Skip to content

Fix undo logic to prevent empty stack access#4

Open
rohith-adluri wants to merge 1 commit intoprateek27:mainfrom
rohith-adluri:memento-bug-fix
Open

Fix undo logic to prevent empty stack access#4
rohith-adluri wants to merge 1 commit intoprateek27:mainfrom
rohith-adluri:memento-bug-fix

Conversation

@rohith-adluri
Copy link
Copy Markdown

Description

This PR fixes an issue in the undo() method of the Caretaker class.

Previously, the condition !history.empty() allowed undo() to execute even when only one state was present. After pop(), this could result in calling peek() on an empty stack, leading to a runtime exception.

Changes

  • Updated condition from !history.empty() to history.size() > 1
  • Ensures a previous state exists before performing undo()
  • Prevents invalid stack access (peek() on empty stack)

Why

The undo() operation should only run when there is a valid previous state to restore. This change improves safety and prevents edge-case failures.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant