在valgrind c++中读取大小为8的无效数据。

问题描述 投票:0回答:1

我得到这个大小为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)
c++ oop valgrind
1个回答
0
投票

在没有看到更多的代码和类定义之前,我无法评论Valgrind的错误。

你正在通过编写非指令性的C++代码来增加你的生活难度。一般来说,如果你确实写了习惯性的代码,并且遵循了最佳实践,那么这些类型的问题很少出现。

  • 不要定义你自己的交换函数,使用 std::swap (@Ted Lyngmo在评论中提到)
  • 不要写intitializer函数。编写构造函数(如果你想重用代码并且至少使用C++11,或许可以委托构造函数)。
  • 不要使用原始指针(我猜测pCargo是在这种原始指针上)。
© www.soinside.com 2019 - 2024. All rights reserved.