簡體   English   中英

常量char *的字符串構造函數更改常量char *的值?

[英]String constructor of constant char* changes value of constant char*?

當前問題

const char *的值似乎正在變為無意義的值。

錯誤的代碼示例

. 以下代碼的目的是創建一個基於值的字符串。 constant; 此過程應使的值保持不變; 但是,它莫名其妙地發生了變化。

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

is being allocated with a call to the "parent" function get_all_processes. 基於變量的被分配給對“父”函數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

and changing the arguments of the function. 消除臨時並更改函數的參數。 myProcessInfo.threads=get_all_processes(("./proc/"+pid_str+"/task").c_str());

變量“ basedir”似乎已經指向您不再擁有的內存。 碰巧的是,它仍然保留您為其分配的值。 通過為字符串“ basedir_str”分配內存,該內存將被其他數據重用和覆蓋。 因此,您的問題出在“ get_process”函數之外。

您如何分配“ basedir”?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM