当前问题
const char* 的值似乎正在变为无意义的值。
错误代码示例
下面代码的目的是创建一个值为basedir的字符串。这个过程应该保持basedir的值不变;但是,它莫名其妙地发生了变化。
ProcessInfo get_process(int pid, const char* basedir) {
cout<<basedir<<endl;
string basedir_str=basedir;
cout<<basedir<<endl;
....}
电流输出
./proc/16224/task
▒▒v▒=+
const char* 到字符串赋值可能有什么问题?
Basedir 是如何设置的
通过调用“父”函数 get_all_processes 来分配变量basedir 。
父函数
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
解决方案
消除临时const char* threadList_fileName并更改get_all_processes函数的参数。
myProcessInfo.threads=get_all_processes(("./proc/"+pid_str+"/task").c_str());