Skip to content

[rcore] Make FileText*() error handling consistent with Text*() helpers - #6210

Merged
raysan5 merged 1 commit into
raysan5:masterfrom
Ne0nWinds:file-text-api-empty-strings
Oct 3, 2026
Merged

raysan5 merged 1 commit into
raysan5:masterfrom
Ne0nWinds:file-text-api-empty-strings

Conversation

@Ne0nWinds

@Ne0nWinds Ne0nWinds commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

This PR addresses two issues:

  1. FileTextFindIndex will dereference a NULL pointer in the following two cases:
    1. the file exists but has empty contents
    2. the file exists but can't be opened (ex. Windows has locked the file)
  2. FileTextReplace will completely overwrite the file contents with garbage if:
    1. the file exists but has empty contents
    2. the search string is of zero-length: ""

FileTextFindIndex

If a file exists but has empty contents, LoadFileText returns a null pointer. FileTextFindIndex directly passes this null pointer into strstr, which crashes the program. This is different from TextFindIndex, which correctly handles zero-length strings.

The solution here is to simply check if LoadFileText returns NULL. This makes FileTextFindIndex and TextFindIndex behave consistently with empty strings, in addition to being more robust against failed file loads.

FileTextReplace

If the file is empty or if the search parameter is a zero-length string, FileTextReplace passes NULL directly into SaveFileText. This NULL pointer gets passed into fprintf with the format string %s. This is undefined behavior in C and does different things depending on the compiler and optimization level. MSVC, for example, writes out the literal string (null) to the file (completely overwriting whatever was there before).

Furthermore, in the event that FileTextReplace hits one of these failure cases, it returns 0, so the caller has no way of knowing something went wrong.

FileTextReplace uses TextReplaceAlloc, which already handles all these edge cases gracefully, so the solution is to check if TextReplaceAlloc returns NULL. Doing so makes FileTextReplace have consistent error handling with TextReplaceAlloc.

@raysan5
raysan5 merged commit a2ee68e into raysan5:master Oct 3, 2026
16 checks passed
@raysan5

raysan5 commented Oct 3, 2026

Copy link
Copy Markdown
Owner

@Ne0nWinds thanks for the review!

@Ne0nWinds
Ne0nWinds deleted the file-text-api-empty-strings branch October 3, 2026 21:11
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