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

fixed #15781: Potential memory issue in StringUtil::format if argument size is greater than 4096 #15903

Merged
merged 2 commits into from
Aug 14, 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
14 changes: 11 additions & 3 deletions native/cocos/base/StringUtil.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -86,12 +86,20 @@ int StringUtil::printf(char *buf, const char *last, const char *fmt, ...) {
}

ccstd::string StringUtil::format(const char *fmt, ...) {
char sz[4096];
va_list args;
va_start(args, fmt);
vprintf(sz, sz + sizeof(sz) - 1, fmt, args);
// Calculate the string length
int length = vsnprintf(nullptr, 0, fmt, args);
if (length <= 0) {
minggo marked this conversation as resolved.
Show resolved Hide resolved
va_end(args);
return "";
dumganhar marked this conversation as resolved.
Show resolved Hide resolved
}
ccstd::string ret;
ret.resize(length, '\0');
int writtenLength = vsnprintf(const_cast<char*>(ret.data()), length + 1, fmt, args);
CC_ASSERT(writtenLength == length);
va_end(args);
return sz;
return ret;
}

ccstd::vector<ccstd::string> StringUtil::split(const ccstd::string &str, const ccstd::string &delims, uint32_t maxSplits) {
Expand Down
Loading
Loading