C++ 常量char*的字符串构造函数更改常量char*的值?

C++ 常量char*的字符串构造函数更改常量char*的值?,c++,string,const-char,C++,String,Const Char,当前问题 const char*的值似乎正在变为一个无意义的值 错误代码示例 下面代码的目的是创建一个值为basedir的字符串。这个过程应该保持basedir的值不变;然而,它莫名其妙地发生了变化 ProcessInfo get_process(int pid, const char* basedir) { cout<<basedir<<endl; string basedir_str=basedir; cout<<basedir<<en

当前问题

const char*的值似乎正在变为一个无意义的值

错误代码示例

下面代码的目的是创建一个值为basedir的字符串。这个过程应该保持basedir的值不变;然而,它莫名其妙地发生了变化

ProcessInfo get_process(int pid, const char* basedir) {
 cout<<basedir<<endl; 
 string basedir_str=basedir;
 cout<<basedir<<endl; 
 ....}
const char*to string赋值有什么问题

如何设置Basedir

./proc/16224/task
▒▒v▒=+
变量basedir通过调用“parent”函数get_all_processes进行分配

父函数

解决方案

消除临时const char*threadList_文件名并更改get_all_processs函数的参数。
myProcessInfo.threads=get_all_进程((“/proc/”+pid_str+“/task”).c_str())

看起来变量“basedir”已经指向您不再拥有的内存。巧合的是,它仍然保留着您分配给它的值。通过为字符串“basedir_str”分配内存,该内存被其他数据重用和覆盖。因此,您的问题不在函数“get_进程”的范围内


如何分配“basedir”?

看起来变量“basedir”已经指向您不再拥有的内存。巧合的是,它仍然保留着您分配给它的值。通过为字符串“basedir_str”分配内存,该内存被其他数据重用和覆盖。因此,您的问题不在函数“get_进程”的范围内


如何分配“basedir”

这是否是由于字符串bet not NULL终止?引用说它会导致未定义的行为。这可能是由于字符串bet not NULL终止吗?参考文献说它会导致未定义的行为。谢谢你的回答,@cwschmidt。在调用父函数时设置basedir。它的值是
(“/proc/”+pid_str+“/task”).c_str()
。我已经用cout语句验证了pid_str是否正确。@Zephyr如果
pid_str
std::string
,则
c_str()
的结果只在下一个
之前有效。它指向的内存将在that@M.M非常感谢!我删除了赋值
const char*threadList_fileName=(“/proc/”+pid_str+“/task”).c_str()
并使用c_str()的即时结果调用父函数。下面的代码解决了这个问题:
myProcessInfo.threads=get_all_进程((“/proc/”+pid_str+“/task”).c_str())(“/proc/”+pid_str+“/task”).c_str()
。我已经用cout语句验证了pid_str是否正确。@Zephyr如果
pid_str
std::string
,则
c_str()
的结果只在下一个
之前有效。它指向的内存将在that@M.M非常感谢!我删除了赋值
const char*threadList_fileName=(“/proc/”+pid_str+“/task”).c_str()
并使用c_str()的即时结果调用父函数。下面的代码解决了这个问题:
myProcessInfo.threads=get_all_进程((“/proc/”+pid_str+“/task”).c_str())
vector<ProcessInfo> get_all_processes(const char* basedir) {
 DIR* dir;
 struct dirent *entry;
 vector<ProcessInfo> totalProcesses;
 //check to see if basedir can be opened
 if((dir =opendir(basedir))!=NULL){

    while((entry = readdir(dir)) != NULL ){
        int pid = atoi (entry->d_name);
        if(pid <=0){
            continue;
        }
        else{

        ProcessInfo currentProcess = get_process(pid, basedir); //<--call to get_process

        totalProcesses.push_back(currentProcess);
        }
    }
    closedir(dir);
}


return totalProcesses;
}
myProcessInfo.threads=get_all_processes(threadList_fileName);
//threadList_filename='./proc/[pid]/task', in this case pid =16224