Search code examples
c++operating-systemnasm

Why Cpp output red font lead to error,but Nasm correct?


I'm a beginner in Cpp and NASM, in a work I try to print some words using red and others default,but when I write print function all by cpp , some words' attribute or value is normal but can't show correctly, after I write print in NASM and link them , it works.

Here is my code,the comment lines are original form I wrote. I'd likely know what leads to this error, thanks very much!

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);
}

Solution

  • The problem is with the definition

    const char* newStr = ("\033[31m" + string(str) + "\033[0m").c_str();
    

    The expression ("\033[31m" + string(str) + "\033[0m") creates a temporary std::string object. Once you have assigned the result of its c_str() call to the pointer variable newStr, the object will end its life and you're left with an invalid pointer.

    Any attempt to dereference that pointer will lead to undefined behavior.

    The simple solution is to use std::string all the time, until you need the pointer and only then use c_str().

    For example:

    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());
        }
    }