我正在为大学写一个项目,一切都完成了,通过了所有测试,运行良好,但 valgrind 告诉我:
==8059== Invalid read of size 8
==8059== at 0x406E4E: RegPoly::getCurrentCoefficient() const (RegPoly.cpp:59)
==8059== by 0x403368: MyPoly::operator+(MyPoly const&) const (MyPoly.cpp:281)
==8059== by 0x403A6D: MyPoly::operator+=(MyPoly const&) (MyPoly.cpp:354)
==8059== by 0x401E20: main (DemoPoly.cpp:50)
==8059== Address 0x5953f50 is 0 bytes after a block of size 16 alloc'd
==8059== at 0x4C27297: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==8059== by 0x4060CD: __gnu_cxx::new_allocator<double>::allocate(unsigned long, void const*) (new_allocator.h:92)
==8059== by 0x405934: std::_Vector_base<double, std::allocator<double> >::_M_allocate(unsigned long) (in /a/fr-05/vol/home/stud/lablabla/CppLab/Ex3/DemoPoly)
==8059== by 0x407355: double* std::vector<double, std::allocator<double> >::_M_allocate_and_copy<__gnu_cxx::__normal_iterator<double const*, std::vector<double, std::allocator<double> > > >(unsigned long, __gnu_cxx::__normal_iterator<double const*, std::vector<double, std::allocator<double> > >, __gnu_cxx::__normal_iterator<double const*, std::vector<double, std::allocator<double> > >) (stl_vector.h:1052)
==8059== by 0x40700E: std::vector<double, std::allocator<double> >::operator=(std::vector<double, std::allocator<double> > const&) (vector.tcc:167)
==8059== by 0x406C5D: RegPoly::RegPoly(RegPoly const&) (RegPoly.cpp:19)
==8059== by 0x4031DB: MyPoly::operator=(MyPoly const&) (MyPoly.cpp:249)
==8059== by 0x403B58: MyPoly::operator*=(MyPoly const&) (MyPoly.cpp:364)
==8059== by 0x401DB6: main (DemoPoly.cpp:44)
这些行:
44 -p3 *= p2; // both are MyPoly objects
50 -p3 += p1;
我有点明白这意味着我正在尝试从已更改的内存中读取(?)但我不明白为什么。我可以发布相关代码,只是,我不确定是哪一部分,因为它会使问题变得混乱。我可以粘贴相关部分,告诉我你需要什么。
谢谢!
编辑:这是代码:
MyPoly& MyPoly::operator *=(const MyPoly& rhs)
{
*this = *this * rhs; // 364
return *this;
}
===================
case PolyInterface::REG:
{
RegPoly *tempReg = dynamic_cast<RegPoly*>(rhs.p_PolyBody); // rhs is an interface, hence the dynamic cast
if (tempReg != NULL)
{
p_PolyBody = new RegPoly(*tempReg); // 249. p_PolyBody is a pointer stored in MyPoly. points to RegPoly object
}
break;
}
===================
RegPoly::RegPoly(RegPoly const& other)
{
gCurrentRank = 0;
gData = other.gData; // 19. gData is a vector<double>
_isZeroPoly = other._isZeroPoly;
}
===================
double RegPoly::getCurrentCoefficient() const
{
return *gDataIterator; // 59. vector<double>::const_iterator
}
===================
newPolyValues.push_back(
p_PolyBody->getCurrentCoefficient() + rhs.p_PolyBody->getCurrentCoefficient());
// 281.
getCurrentCoefficient()
编辑:返回时我也得到了这gData[gCurrentRank]
意味着它与 gData 本身的位置有关,对吗?
RegPoly:
std::vector<double> gData;
std::vector<double>::iterator gDataIterator;
int gCurrentRank;
bool _isZeroPoly; // Inherited from the interface