因此,我正在创建一个函数,仅当字符串是向量中尚未包含的唯一字符串时,才会将新字符串添加到字符串向量中。这是我的代码:
void CityMapper::addToVector(string& s)
{
bool newWord = true;
if(numAirports > 0)
{
for(int i = 0; i < numAirports; i++)
{
if(airportNames[i].compare(s) == 0)
newWord = false;
}
}
if(newWord == true)
{
airportNames.pushBack(s);
numAirports++;
}
}
airportNames 是字符串的向量。当我运行该程序时,它在 Valgrind 中出现以下错误:
Process Terminating with default action of signal 11 (SIGSEGV)
Access not within mapped region at address 0x0
在此之前,此错误出现在 Valgrind 终端中:
Invalid Read of Size 8
两者都发生在 string.compare() 行。有谁知道为什么会发生这种情况?我还尝试了参数中没有 & 符号的函数。
编辑:我接受了 Derek 的建议并做了他所有的改变。现在程序以不同的方法进行段错误,我从文件中读取字符串。这是该函数的代码:
void CityMapper::getCities()
{
ifstream fin;
fin.open(flightDataFile);
fin >> numAirports;
string tempCity1, tempCity2, tossout;
while(getline(fin, tempCity1, ','))
{
fin.ignore(1);
getline(fin, tempCity2, ',');
fin.ignore(1);
getline(fin, tossout, '\n');
addToVector(tempCity1);
addToVector(tempCity2);
}
}
以下是来自 Valgrind 的错误消息:
==8357== Use of uninitialised value of size 8
==8357== at 0x4EF158B: std::basic_string<char, std::char_traits<char>,
std::allocator<char> >::basic_string(std::string const&) (in /usr/lib/x86_64-linux-
gnu/libstdc++.so.6.0.17)
==8357== by 0x402214: CityMapper::getCities() (in
/home/charlie/NetBeansProjects/Lab4/Lab4)
==8357== by 0x401EB7: CityMapper::run() (in /home/charlie/NetBeansProjects/Lab4/Lab4)
==8357== by 0x4050A0: main (in /home/charlie/NetBeansProjects/Lab4/Lab4)
==8357==
==8357== Invalid read of size 4
==8357== at 0x4EF158B: std::basic_string<char, std::char_traits<char>,
std::allocator<char> >::basic_string(std::string const&) (in /usr/lib/x86_64-linux-
gnu/libstdc++.so.6.0.17)
==8357== by 0x402214: CityMapper::getCities() (in
/home/charlie/NetBeansProjects/Lab4/Lab4)
==8357== by 0x401EB7: CityMapper::run() (in /home/charlie/NetBeansProjects/Lab4/Lab4)
==8357== by 0x4050A0: main (in /home/charlie/NetBeansProjects/Lab4/Lab4)
==8357== Address 0xfffffffffffffff8 is not stack'd, malloc'd or (recently) free'd
==8357==
==8357==
==8357== Process terminating with default action of signal 11 (SIGSEGV)
==8357== Access not within mapped region at address 0xFFFFFFFFFFFFFFF8
==8357== at 0x4EF158B: std::basic_string<char, std::char_traits<char>,
std::allocator<char> >::basic_string(std::string const&) (in /usr/lib/x86_64-linux-
gnu/libstdc++.so.6.0.17)
==8357== by 0x402214: CityMapper::getCities() (in
/home/charlie/NetBeansProjects/Lab4/Lab4)
==8357== by 0x401EB7: CityMapper::run() (in /home/charlie/NetBeansProjects/Lab4/Lab4)
==8357== by 0x4050A0: main (in /home/charlie/NetBeansProjects/Lab4/Lab4)