c++ - 当我调用不相关的方法时,c 字符串的值发生变化

标签 c++ string c-strings

我正在处理一个头文件,该文件定义了一个命名空间,其中定义了一些 c 字符串。

namespace env {
    const char* C_NAME;
    const char* SYS_DRIVE;
    const char* PROCESSOR;
    const char* PROCESSOR_ARCHITECTURE;
    const char* OSNAME;
}

我的主要功能是这样的:

int main(int argc, char* argv[], char* env[]) {
    initialize_environment_vars(env);

    cout << "C_NAME\t\t\t" << env::C_NAME << endl;
    /*...*/

    return 0;
}

我的问题是我在 initialize_environment_vars() 中初始化的字符串没有我想要的值。

void initialize_environment_vars(char* env[]) {
    int id = PRIVATE::findEntry(env, "COMPUTERNAME");
    env::C_NAME = (str::getAfter(env[id], "=")).c_str(); // getAfter() returns a string
    //std::cout << env::C_NAME << std::endl; //Right value!!!

    id = PRIVATE::findEntry(env, "SystemDrive");
    std::cout << env::C_NAME; //Value at env[id]

    /*Here the other constants are initialized in the same way.*/
}

我发现在函数 initialize_environment_vars() 中,变量具有正确的值,直到我调用函数 findEntry() 来查找另一个条目。

int PRIVATE::findEntry(const char* const arr[], std::string toFind) {
    bool found = false;
    int i = 0;
    std::string actual;
    while(arr[i] && !found) {
        actual = arr[i];
        if(str::contains(actual, toFind)) {
            found = true;
            break;
        }
        i++;
    }

    if(found)
        return i;
    else { /*Error message and exit program*/ }
}

看完这篇文章,string::c_str query , 我还认为我在 initialize_environment_vars() 中使用 .c_str() 是错误的,因为返回的字符串在调用 .c_str 后会被销毁(),但这似乎并非如此,因为 env::C_NAMEmain() 中有效。

因此我有两个问题:

  1. 为什么我的 PRIVATE::findEntry(const char* const [], std::string) 函数会按照我使用的方式更改 env::C_NAME 的值它在上面,即使它只返回一个 int 并且不修改数组或条目?
  2. 为什么 env::C_NAME 在“main()”中仍然有效?在 str::getAfter(const std::string&, std::string) 返回的字符串的析构函数被调用后它不应该变得无效吗? (已回答)

最佳答案

Why does my PRIVATE::findEntry(const char* const [], std::string) function change the value of env::C_NAME the way I use it above, even though it only returns an int and does not modify the array nor the entries?

如果字符串被破坏或修改,则不再保证 c_str() 的返回值有效。

Why is env::C_NAME still valid in 'main()'? Should it not become invalid after the destructor of the string that str::getAfter(const std::string&, std::string) returns is called?

不是。它只是碰巧包含了你想要它包含的东西,而不是碰巧包含了你想要它包含的东西以外的东西。如果您在可能正面朝上的情况下掷硬币,那么您正在做一些错误的事情,但它可能会奏效。如果你再做一次,它可能会发生不起作用。这就是为什么我们不做这样的事情。

不要混淆代码的行为方式与您期望代码的行为方式。在我们期望事情无效的情况下,我们不知道代码的实际行为。它可能碰巧做了一些好事,也可能碰巧做了一些灾难性的事情。它可能会随着编译器选项、编译器版本、平台或其他参数而改变。

您有两个明显的选择。您可以将这些变量的类型从 const char * 更改为 std::string 或者您可以使用 mallocstrdup 分配将保持有效的内存。

关于c++ - 当我调用不相关的方法时,c 字符串的值发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35948163/

相关文章:

c++ - HDF5挂载文件(带H5Fmount)

c# - NativeWindow 等效项

c++ - 相当于 Windows 上的 select for Pipes

c++ - 在命令中运行 cmake 'make' 不起作用

c - 将 strstr() 函数与指针一起使用

string - 显示没有毫秒的 CFGregorianDate

objective-c - 从 c char[] 获取 objective-c nsstring

c++ - 对混合(空和非空)cstring 数组进行排序

在 C 中使用 ## 运算符连接字符串

c - 字符串大小