Skip to content

fix: keyTap throws "Invalid key code" for valid keys due to dangling pointer#792

Closed
ssxv wants to merge 1 commit into
octalmage:masterfrom
ssxv:fix/keyTap-dangling-pointer-issue
Closed

fix: keyTap throws "Invalid key code" for valid keys due to dangling pointer#792
ssxv wants to merge 1 commit into
octalmage:masterfrom
ssxv:fix/keyTap-dangling-pointer-issue

Conversation

@ssxv

@ssxv ssxv commented May 8, 2026

Copy link
Copy Markdown

Issue: #789

Description

robot.keyTap("tab") and other valid multi-character key names throw Error: Invalid key code specified due to a dangling pointer bug in keyTapWrapper.

Root Cause

In src/robotjs.cc, the keyTapWrapper function was doing this:

Napi::String kstr(env, info[0].ToString());
k = kstr.Utf8Value().c_str();

kstr.Utf8Value() returns a temporary std::string. Taking .c_str() from it gives a raw pointer that becomes invalid as soon as the temporary is destroyed - at the end of that same statement. By the time k is passed to CheckKeyCodes(), it is a dangling pointer pointing to freed memory, causing the key name lookup against the key_names table to fail unpredictably.

This is a non-deterministic bug - it may work in some environments depending on whether the freed memory has been overwritten.

Fix

Changed keyTapWrapper to store the string in a named std::string that lives for the full function scope, matching the pattern already used in keyToggleWrapper:

std::string kstr = info[0].As<Napi::String>();
k = kstr.c_str();

Files Changed

  • robotjs.cc - keyTapWrapper function only

Testing

Verified that robot.keyTap("tab") and other named keys (enter, backspace, escape, etc.) no longer throw Invalid key code specified after the fix.

@ssxv

ssxv commented May 8, 2026

Copy link
Copy Markdown
Author

@octalmage

Please check this. Key Tap isn't working. Its one of basic functionalities of robotjs which is breaking In v0.7.0

@octalmage

Copy link
Copy Markdown
Owner

Thanks for the PR! I had fixed this in #784 and just cherry-picked the commit into master (as well as a few other build fixes). I will work on getting a fix deployed to npm!

@octalmage

Copy link
Copy Markdown
Owner

robotjs@0.7.1 deployed to npm which resolve this issue, thanks again!!

@octalmage octalmage closed this May 8, 2026
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.

2 participants