誰能告訴我爲什麼使用從c_str()返回的const char *作爲stat(const char *,stat *)中的參數導致程序段錯誤?我想我已經縮小了由於該線引起的段錯誤,但我不確定要使用什麼。我嘗試使用strcpy()將字符串複製到一個字符數組中,但這只是導致程序在方法返回時發生段錯誤,這並不好。segd當使用std :: string.c_str()作爲另一個方法的參數
DIR * dir_p;
struct dirent *dir_entry_p;
list<string> files;
dir_p = opendir(".");
//push all file names to a list
while((dir_entry_p = readdir(dir_p))!=NULL){
string name = dir_entry_p->d_name;
files.push_front(name);
}
closedir(dir_p);
files.sort();
//count total blocks
//iterate through list
map<string,struct stat*> fileStats;
struct stat * entry;
for(list<string>::iterator it = files.begin(); it != files.end(); it++){
stat(it->c_str(),entry);
fileStats[*it]=entry;
cout<<entry->st_blocks<<" "<<*it<<endl;
}
編譯所有警告和調試信息(例如'g ++ -Wall -g')。改進代碼直到不給出警告。使用[valgrind](http://valgrind.org/)和你的**調試器**(例如'gdb') –
@ H2CO3,對於如何避免「未格式化,無法讀取的混亂」的建議,我很樂意提供。簡單地說,這不是我以後編寫代碼時可以考慮的事情。事實上,你的評論簡直沒有幫助和煽動性。 – LucienK