The Current Issue
The value of a const char* seems to be changing to a nonsensical value.
Faulty Code Example
The intention of the code below is to create a string with the value of basedir. This process should keep the value of basedir constant; however, it inexplicably changes.
ProcessInfo get_process(int pid, const char* basedir) {
cout<<basedir<<endl;
string basedir_str=basedir;
cout<<basedir<<endl;
....}
Current Output
./proc/16224/task
▒▒v▒=+
What could be wrong with the const char* to string assignment?
How Basedir Is Set
The variable basedir is being allocated with a call to the "parent" function get_all_processes.
Parent Function
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;
}
Call to Parent Function
myProcessInfo.threads=get_all_processes(threadList_fileName);
//threadList_filename='./proc/[pid]/task', in this case pid =16224
Solution
Eliminating the temporary const char* threadList_fileName and changing the arguments of the get_all_processes function.
myProcessInfo.threads=get_all_processes(("./proc/"+pid_str+"/task").c_str());