我在AccountMap.h和AccountMap.cpp中有一个类AccountMap。它从二进制文件中读取内容(这是可以的)并输出内容。它在c++编译器上运行得很好,但是当我在一个函数中使用new操作符进行10次迭代时,在sun c++ CC编译器上出现了seg故障。如果我忽略segfault,它仍然输出正确的东西。这是我的AccountMap.h:
#ifndef account_map
#define account_map
#include <iostream>
#include <map>
#include <cstring>
#include "Account.h"
using namespace std;
struct CompareCharArrays
{
bool operator()(const char* a, const char* b) const //overloading () operator
{
if((strcmp(a,b) < 0))
{
return true;
}
return false;
}
};
class AccountMap
{
public:
~AccountMap(); //destructor
void loadData(const char *); //loads data from a given file
int countRecs(const char *); //counts total number of records in the given file
void displayData(); //displays data
private:
multimap<const char *, Account, CompareCharArrays> accounts; //a multipmap
Account** account_manager; //two-D array of accounts
char** key_manager; //two-D array of keys
int total_accounts; //total number of accounts
};
#endif
这是我的AccountMap.cpp函数,导致段错误:
void AccountMap::loadData(const char * file) //loads data from a given file
{
int num = countRecs(file); //total no of records in the file
ifstream in(file, ios::in | ios::binary);
if(!in)
{
cerr<<"File doesn't exist!"<<endl;
exit(1);
}
this->account_manager = new (nothrow) Account*[num];
if(this->account_manager == NULL)
{
exit(1);
}
this->key_manager = new (nothrow) char*[num]; //seg fault here during 10th iteration
if(this->key_manager == NULL)
{
exit(1);
}
simplyfy_data acc;
this->total_accounts = 0;
while(in.read((char*)&acc, sizeof(simplyfy_data)))
{
this->account_manager[this->total_accounts] = new (nothrow) Account;
if(this->account_manager[this->total_accounts] == NULL)
{
exit(1);
}
this->key_manager[this->total_accounts] = new (nothrow) char;
if(this->key_manager[this->total_accounts] == NULL)
{
exit(1);
}
string date;
int len = strlen(acc.dob);
for(int i = 0; i < len; i++)
{
date.push_back(acc.dob[i]);
}
account_manager[this->total_accounts]->set_data(acc.number,acc.name,acc.sex,date,acc.address,acc.balance);
strcpy(key_manager[this->total_accounts],acc.name);
this->accounts.insert(pair<const char* const, Account>(key_manager[this->total_accounts],(*account_manager[this->total_accounts]))); //inserting
this->total_accounts++;
}
in.close();
}
错误是:
signal SEGV (no mapping at the fault address) in realfree at 0xa2958440
0xa2958440: realfree+0x0068: ld [%o7 + 8], %o5
您为一个字符分配空间…
this->key_manager[this->total_accounts] = new (nothrow) char;
…然后复制许多…
strcpy(key_manager[this->total_accounts],acc.name);
您应该使用std::string
和std::vector
,并避免在multimap
键中使用new
和const char*
:您将更有可能避免错误(包括内存泄漏,特别是如果您有异常)。