我是Cpp和NASM的初学者,在工作中我尝试使用红色和其他默认值打印一些单词,但是当我全部使用cpp编写打印功能时,某些单词的属性或值是正常的但无法正确显示,在我在 NASM 中编写 print 并链接它们后,它就可以工作了。
这是我的代码,注释行是我写的原始形式。我可能知道是什么导致了这个错误,非常感谢!
extern "C" {
void print(const char*);
void print_red(const char*);
}
// 全局函数
// 1.利用汇编打印
void printOut(const char* str, bool isDir = false) {
if (isDir) {
// const char* newStr = ("\033[31m" + string(str) + "\033[0m").c_str();
const char* newStr = str;
print_red(newStr);
} else {
print(str);
}
// print(str);
}
问题在于定义
const char* newStr = ("\033[31m" + string(str) + "\033[0m").c_str();
表达式
("\033[31m" + string(str) + "\033[0m")
创建一个 temporary std::string
对象。一旦您将其 c_str()
调用的结果分配给指针变量 newStr
,该对象将结束其生命,并且您将得到一个无效的指针。
任何取消引用该指针的尝试都将导致未定义的行为。
简单的解决方案是一直使用
std::string
,直到需要指针时才使用 c_str()
。
例如:
void printOut(const std::string& str, bool isDir = false) {
if (isDir) {
std::string newStr = "\033[31m" + str + "\033[0m";
print_red(newStr.c_str());
} else {
print(str.c_str());
}
}