我得到这个大小为8的无效读数,不知道如何去解决这个问题,我是一般的编程新手。以下是问题所显示的代码。
void Cargo::initialize(const char* desc, double weight)
{ setDesc(desc);
setWeight(weight);
}
void Cargo::setDesc(const char* description)
{
if (strlen(description) <= MAX_DESC)
{
strncpy(m_description, description, MAX_DESC + 1);
}
}
void Cargo::setWeight(double weight){
if (MIN_WEIGHT <= weight && weight <= MAX_WEIGHT)
m_weight = weight;
else
m_weight = MIN_WEIGHT;
}
double Cargo::getWeight() const
{
return m_weight;
}
bool Train::swapCargo(Train &other)
{
bool isEmpty = false;
if ((isValid() && other.isValid()))
{
Cargo temp;
temp.initialize(pCargo->getDesc(), pCargo->getWeight());
pCargo->initialize(other.pCargo->getDesc(), other.pCargo->getWeight());
other.pCargo->initialize(temp.getDesc(), temp.getWeight());
isEmpty = true;
return isEmpty;
}
return isEmpty;
}
从valgrind的错误,我相信问题可能是来自swapCargo的temp,但我不确定。如果我调用一个类Cargo的temp,我必须清除它,还是只有当我使用 "new "的时候。
==119155== Invalid read of size 8
==119155== at 0x400B8C: sdds::Cargo::getWeight() const (Cargo.cpp:32)
==119155== by 0x400F6E: sdds::Train::swapCargo(sdds::Train&) (Train.cpp:94)
==119155== by 0x401A60: main (main_prof.cpp:131)
==119155== Address 0x18 is not stack'd, malloc'd or (recently) free'd
==119155==
==119155==
==119155== Process terminating with default action of signal 11 (SIGSEGV)
==119155== Access not within mapped region at address 0x18
==119155== at 0x400B8C: sdds::Cargo::getWeight() const (Cargo.cpp:32)
==119155== by 0x400F6E: sdds::Train::swapCargo(sdds::Train&) (Train.cpp:94)
==119155== by 0x401A60: main (main_prof.cpp:131)
==119155== If you believe this happened as a result of a stack
==119155== overflow in your program's main thread (unlikely but
==119155== possible), you can try to increase the size of the
==119155== main thread stack using the --main-stacksize= flag.
==119155== The main thread stack size used in this run was 8388608.
==119155==
==119155== HEAP SUMMARY:
==119155== in use at exit: 0 bytes in 0 blocks
==119155== total heap usage: 3 allocs, 3 frees, 96 bytes allocated
==119155==
==119155== All heap blocks were freed -- no leaks are possible
==119155==
==119155== For lists of detected and suppressed errors, rerun with: -s
==119155== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
在没有看到更多的代码和类定义之前,我无法评论Valgrind的错误。
你正在通过编写非指令性的C++代码来增加你的生活难度。一般来说,如果你确实写了习惯性的代码,并且遵循了最佳实践,那么这些类型的问题很少出现。
std::swap
(@Ted Lyngmo在评论中提到)