Can anyone tell me why using returned const char* from c_str() as an argument in stat(const char*, stat*) causes the program to segfault? I think I've narrowed down my segfault to being caused by that line, but I'm not sure what to use instead. I tried copying the string into a character array using strcpy(), but that just caused the program to segfault as the method was returning, which isn't much better.
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;
}
I don't think it's the c_str()
making troubles here, but how you're using struct stat
.
You should create a struct stat
instance and pass it's address:
// ...
//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;
}
What you're doing is letting stat()
write to the address coming from an uninitialized pointer (which will most likely end up in a segfault).
Note that you'll also need to change the map type to get this working.