ARM架构Mac与x86 Linux下C++程序输出不一致问题求助
问题根源
你的代码中trim函数存在未定义行为,直接导致了Mac ARM设备上的随机错误:
constexpr char SPACE = ' '; const size_t first_index = input.find_first_not_of(&SPACE);
std::string::find_first_not_of接受const char*参数时,会将其当作以\0结尾的C风格字符串处理,但&SPACE仅指向单个空格字符,后续内存是未初始化的随机数据。函数会错误地将这些随机字符纳入匹配范围,导致find_first_not_of或find_last_not_of返回意外的索引值,进而截断字符串(比如把Hello变成Hell)。
这种未定义行为的表现具有随机性:Linux x86和Mac Rosetta环境下,&SPACE后续内存恰好没有干扰字符,所以结果正常;但Mac原生ARM环境中,随机内存里偶尔会出现匹配字符,导致输出错误。
代码修正方案
只需要修改trim函数中find_first_not_of和find_last_not_of的参数,直接传递char类型的SPACE(利用函数的char重载版本),而非其地址:
string trim(const string& input) { if (input.empty()) { return ""; } constexpr char SPACE = ' '; const size_t first_index = input.find_first_not_of(SPACE); // 去掉&符号 if (first_index == string::npos) { return ""; } const size_t last_index = input.find_last_not_of(SPACE); // 去掉&符号 return input.substr(first_index, last_index - first_index + 1); }
也可以直接传递字符串字面量" ",效果相同:
const size_t first_index = input.find_first_not_of(" "); const size_t last_index = input.find_last_not_of(" ");
修改后,两台设备上使用g++ -std=c++20 -o hello main.cpp编译运行,都会稳定输出预期的[Hello, world]。
内容的提问来源于stack exchange,提问作者Kurisuchan
相关产品推荐
相关产品推荐

