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

时间:2016-02-28 00:02:13

标签: 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<<endl; 
 ....}

当前输出

./proc/16224/task
▒▒v▒=+

const char *到字符串赋值有什么问题?

如何设置基础

变量 basedir 正在通过调用“父”函数get_all_processes进行分配。

家长功能

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

1 个答案:

答案 0 :(得分:4)

它看起来像变量&#34; basedir&#34;已经指向你不再拥有的记忆了。巧合的是它仍然保留了你赋予它的价值。通过为字符串分配内存&#34; basedir_str&#34;此内存被其他数据重用和覆盖。所以你的问题不在于函数&#34; get_process&#34;。

你如何分配&#34; basedir&#34;?

相关问题