2013-11-20 31 views
0

誰能告訴我爲什麼使用從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; 
} 
+1

編譯所有警告和調試信息(例如'g ++ -Wall -g')。改進代碼直到不給出警告。使用[valgrind](http://valgrind.org/)和你的**調試器**(例如'gdb') –

+0

@ H2CO3,對於如何避免「未格式化,無法讀取的混亂」的建議,我很樂意提供。簡單地說,這不是我以後編寫代碼時可以考慮的事情。事實上,你的評論簡直沒有幫助和煽動性。 – LucienK

回答

6

我不認爲這裏的c_str()使煩惱,但你如何使用struct stat
您應該創建一個struct stat實例,並通過它的地址:

// ... 

//iterate through list 
map<string,struct stat> fileStats; 
for(list<string>::iterator it = files.begin(); it != files.end(); it++){ 
    struct stat entry; 
    stat(it->c_str(),&entry); 
    fileStats[*it]=entry; 
    cout<<entry.st_blocks<<" "<<*it<<endl; 
} 

你正在做什麼是讓stat()寫入到從一個未初始化的指針(這將最有可能在段錯誤結束)傳來的地址。

請注意,您還需要更改地圖類型才能使其工作。

+0

初始化指針可修復段錯誤。謝謝。 – LucienK

+0

@Dazedy小心你如何初始化指針(內存泄漏等)。我發佈的代碼應該可以正常工作,並且不會增加額外的開銷。 –

+0

好的,謝謝你的幫助。 – LucienK

相關問題