Skip to content

raygui: fix buffer overflow crash in TextBox when string is smaller than textSize - #547

Merged
gen2brain merged 1 commit into
gen2brain:masterfrom
shdynila:fix-raygui-textbox-buffer-overflow
Jun 1, 2026
Merged

raygui: fix buffer overflow crash in TextBox when string is smaller than textSize#547
gen2brain merged 1 commit into
gen2brain:masterfrom
shdynila:fix-raygui-textbox-buffer-overflow

Conversation

@shdynila

@shdynila shdynila commented May 31, 2026

Copy link
Copy Markdown
Contributor

Description

Fixes a heap corruption/buffer overflow crash when calling raygui.TextBox with a string that is shorter than the requested textSize (e.g., an empty string "" with a textSize of 25).

Root Cause

In Go, bs := []byte(*text) creates a byte slice whose size is bound to the string's current length, rather than the requested textSize.
If len(bs) is smaller than textSize, the C function GuiTextBox receives a pointer to a small Go-allocated buffer but expects it to be at least textSize bytes. When typing a character, GuiTextBox writes out-of-bounds, corrupting the Go heap and causing access violations / segmentation faults.

Solution

  1. Ensured Minimum Buffer Capacity: If the string slice bs is smaller than textSize, it is re-allocated to have a length of at least textSize (newBs := make([]byte, textSize); copy(newBs, bs)).
  2. Migrated to C-Heap Allocation (C.CString): Instead of passing a Go garbage-collected slice pointer directly to C (&bs[0]), which violates cgo pointer-passing rules for mutable buffers, we now copy it safely to the C-heap using C.CString(string(bs)).
  3. Safe Memory Cleanup & Synchronization: We defer freeing the C-allocated memory using C.free and successfully copy the updated string back into Go memory with *text = C.GoString(ctext) after GuiTextBox executes.

@shdynila
shdynila marked this pull request as ready for review May 31, 2026 08:13
@shdynila
shdynila force-pushed the fix-raygui-textbox-buffer-overflow branch from 92b103c to 2e580b0 Compare May 31, 2026 16:56
@shdynila
shdynila force-pushed the fix-raygui-textbox-buffer-overflow branch from 2e580b0 to 34bab32 Compare May 31, 2026 19:45
@gen2brain
gen2brain merged commit 8d36eb1 into gen2brain:master Jun 1, 2026
10 checks passed
@gen2brain

Copy link
Copy Markdown
Owner

Thanks, I am merging this. Note that raygui in this state is contributed; before, there was a plain Go code that just called into the raylib bindings, mimicking what the C API did. But, maintaining and following upstream was an issue, so I accepted the CGo solution that worked for users. Perhaps, introducing that again in the age of AI, where it is not that difficult to follow, is again a good idea.

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.

3 participants