我在AccountMap.h和AccountMap.cpp中有一个AccountMap类。它从二进制文件中读取内容(可以)并输出内容。它在g ++编译器上运行得非常好,但是当我在函数之一中使用new运算符进行10次迭代时,却在sun c ++ CC编译器上出现了段错误。如果我忽略段错误,它仍然会输出正确的内容。这是我的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函数,导致seg错误:
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
,并避免new
与const char*
中multimap
键:你会大规模更有可能避免的错误(包括内存泄漏,特别是如果你有例外)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句