Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[rtext] TextFormat() warn user if buffer overflow occured. #3399

Merged
merged 6 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/rcore.c
Original file line number Diff line number Diff line change
Expand Up @@ -2874,6 +2874,7 @@ static void PlayAutomationEvent(unsigned int frame)
#if !defined(SUPPORT_MODULE_RTEXT)
// Formatting of text with variables to 'embed'
// WARNING: String returned will expire after this function is called MAX_TEXTFORMAT_BUFFERS times

const char *TextFormat(const char *text, ...)
{
#ifndef MAX_TEXTFORMAT_BUFFERS
Expand All @@ -2892,12 +2893,21 @@ const char *TextFormat(const char *text, ...)

va_list args;
va_start(args, text);
vsnprintf(currentBuffer, MAX_TEXT_BUFFER_LENGTH, text, args);
int charCountRequired = vsnprintf(currentBuffer, MAX_TEXT_BUFFER_LENGTH, text, args);
va_end(args);

// If charCountRequired is larger than the MAX_TEXT_BUFFER_LENGTH, then overflow occured
if(charCountRequired > MAX_TEXT_BUFFER_LENGTH)
{
// We are going to insert [TRUN] at the end of the string so the user knows what happened
char *truncBuffer = buffers[index] + MAX_TEXT_BUFFER_LENGTH - 7; // 7 = six letters + '\0'
sprintf(truncBuffer, "[TRUN]");
}

index += 1; // Move to next buffer for next function call
if (index >= MAX_TEXTFORMAT_BUFFERS) index = 0;

return currentBuffer;
}

#endif // !SUPPORT_MODULE_RTEXT
11 changes: 10 additions & 1 deletion src/rtext.c
Original file line number Diff line number Diff line change
Expand Up @@ -1371,15 +1371,24 @@ const char *TextFormat(const char *text, ...)

va_list args;
va_start(args, text);
vsnprintf(currentBuffer, MAX_TEXT_BUFFER_LENGTH, text, args);
int charCountRequired = vsnprintf(currentBuffer, MAX_TEXT_BUFFER_LENGTH, text, args);
va_end(args);

// If charCountRequired is larger than the MAX_TEXT_BUFFER_LENGTH, then overflow occured
if(charCountRequired > MAX_TEXT_BUFFER_LENGTH)
{
// We are going to insert [TRUN] at the end of the string so the user knows what happened
char *truncBuffer = buffers[index] + MAX_TEXT_BUFFER_LENGTH - 7; // 7 = six letters + '\0'
sprintf(truncBuffer, "[TRUN]");
}

index += 1; // Move to next buffer for next function call
if (index >= MAX_TEXTFORMAT_BUFFERS) index = 0;

return currentBuffer;
}


// Get integer value from text
// NOTE: This function replaces atoi() [stdlib.h]
int TextToInteger(const char *text)
Expand Down