Skip to content

fix(GFX_Button): initialize currstate/laststate - #513

Open
94xhn wants to merge 1 commit into
adafruit:masterfrom
94xhn:fix/button-uninitialized-state
Open

fix(GFX_Button): initialize currstate/laststate#513
94xhn wants to merge 1 commit into
adafruit:masterfrom
94xhn:fix/button-uninitialized-state

Conversation

@94xhn

@94xhn 94xhn commented Jul 11, 2026

Copy link
Copy Markdown

Fixes #401.

Problem

Adafruit_GFX_Button's constructor only initializes _gfx:

Adafruit_GFX_Button::Adafruit_GFX_Button(void) { _gfx = 0; }

currstate/laststate (declared in Adafruit_GFX.h with no default member initializer) are left as indeterminate memory. justPressed()/justReleased() read them:

bool Adafruit_GFX_Button::justPressed() { return (currstate && !laststate); }
bool Adafruit_GFX_Button::justReleased() { return (!currstate && laststate); }

If either is called before the first press() call, the result depends on whatever garbage happened to be on the stack/heap at construction time - a button that was never touched can spuriously report a press or release transition.

Fix

Initialize both to false in the constructor, matching the "not pressed, no prior state" starting condition every other code path already assumes.

Test plan

No hardware handy, so I verified the logic with a standalone harness modeling the class's exact fields/methods: before the fix, constructing a Button over deliberately non-zeroed memory and calling justPressed() before any press() call can return true; after the fix, it correctly returns false.

Disclosure

Generative AI (Claude) was used to help investigate this issue, implement, and verify this fix. All changes were reviewed by me before submission.

Adafruit_GFX_Button's constructor only initializes _gfx, leaving
currstate/laststate as indeterminate memory. justPressed()/
justReleased() read these before the first press() call, so they can
report a spurious press/release transition on a button that was never
actually touched.

Fixes adafruit#401

Signed-off-by: 94xhn <87560781+94xhn@users.noreply.github.com>
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.

In Adafruit_GFX.cpp, variables currstate and laststate are not initialized

1 participant