Niestety mam problem w kodzie, gdyż w momencie kiedy zwalniam wskaźnik na obiekt vector<char*> pojawia się Bus error: 10
Kiedy nie usuwam obiektu wszystko jest ok. Wielokrotnie pisałem podobny kod i nigdy nie miałem tego typu problemu :(
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <dirent.h>
#include <sys/stat.h>
#define DEBUG
#ifdef DEBUG
#define ECHOD(NAME, VALUE) cout << "*** DEBUG ***" << " NR LINE: " << __LINE__ << " IN FUNCTION: " << __FUNCTION__ << " NAME: " << NAME << " VALUE: " << VALUE << endl;
#else
#define ECHOD(NAME, VALUE)
#endif
using namespace std;
class MCScandir;
class MCScandir {
private:
const char* dirpath;
const char* filename;
MCScandir(const char* dirpath_) : dirpath(dirpath_) {}
public:
void* object;
static MCScandir& createScandir(const char* dirpath_) { dirpath_ = (dirpath_ == NULL)?"./":dirpath_; static MCScandir sd(dirpath_); return sd; }
~MCScandir() {}
int scan(vector<char*> &v, int(*sd)(const MCScandir& o) = NULL);
const char* getFilename() const { return filename; }
};
int filter(const MCScandir& o);
struct fdata {
const char* fname;
int fsize;
};
int main(int argc, const char* argv[]) {
int i = 0;
MCScandir sd = MCScandir::createScandir(argv[1]);
vector<char*> *v = new vector<char*>;
int(*filter_search_files)(const MCScandir& o) = &filter;
// const char* find = "include";
//string* find = new string("include");
//string find("include");
struct fdata *fnd;
fnd->fname = "include";
fnd->fsize = 1024;
sd.object = (struct fdata*)fnd;
sd.scan(*v, NULL);
for(i = 0; i < v->size(); i++) {
cout << (*v)[i] << endl;
delete (*v)[i];
}
//delete v;
return 0;
}
int MCScandir::scan(vector<char*> &v, int(*sd)(const MCScandir& o)) {
DIR* dh = opendir(dirpath);
struct dirent* d = NULL;
char* fname = NULL;
struct stat st;
if(dh == NULL) {
return -1;
}
while(d = readdir(dh)) {
filename = d->d_name;
lstat(filename, &st);
if(S_ISDIR(st.st_mode))
continue;
if(sd == NULL) {
fname = new char[strlen(filename)];
strcpy(fname, filename);
v.push_back(fname);
ECHOD("NULL::fname:", fname);
} else if(sd(*this)) {
fname = new char[strlen(filename)];
strcpy(fname, filename);
v.push_back(fname);
ECHOD("PTR_FUNC::fname", fname);
}
}
closedir(dh);
return v.size();
}
int filter(const MCScandir& o) {
ECHOD("filename", o.getFilename())
string line;
int fsize = 0;
fstream f(o.getFilename());
if(!f.is_open()) {
return 0;
}
if(o.object == NULL)
return 0;
f.seekg(0, ios::end);
fsize = f.tellg();
f.seekg(0, ios::beg);
ECHOD("fsize", fsize)
while(getline(f, line)) {
if((line.find(static_cast<struct fdata*>(o.object)->fname) != string::npos) && (static_cast<struct fdata*>(o.object)->fsize > fsize)) {
f.close();
return 1;
}
}
f.close();
return 0;
}