问题:

我有一个我没想到的怪异问题。我有一个类叫做答案
在 header 中是这样的:

class Answer
{
    char* aText;
    bool b_correct;
public:
    Answer():aText(0){;}  //default constructor
}

主要(测试)驱动程序代码是这样的:
int main(void)
{

    static const unsigned int MAX_ANSWERS = 5;
    Answer answers[MAX_ANSWERS];
}

我得到的(意外的)怪异是发生了分配,并且我的代码中还没有使用新的地方。我猜char *正在初始化列表中调用它。

我正在使用valgrind测试我的代码,并且得到11个alloc和10个free。当我删除:aText(0)的初始化程序时,多余的分配消失了。

我知道这是构造错误的代码。我正在按照类(class)大纲来学习如何用C++编写。有人可以帮我理解内存的分配方式,或者在初始化列表期间发生什么情况以引起对new的调用吗?

我知道错误来自显示的代码。我知道在编译和运行此代码时会发生额外的分配。

Valgrind输出:
==12598== Memcheck, a memory error detector
==12598== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==12598== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==12598== Command: ./Answers
==12598==
==12598==
==12598== HEAP SUMMARY:
==12598==     in use at exit: 72,704 bytes in 1 blocks
==12598==   total heap usage: 1 allocs, 0 frees, 72,704 bytes allocated
==12598==
==12598== LEAK SUMMARY:
==12598==    definitely lost: 0 bytes in 0 blocks
==12598==    indirectly lost: 0 bytes in 0 blocks
==12598==      possibly lost: 0 bytes in 0 blocks
==12598==    still reachable: 72,704 bytes in 1 blocks
==12598==         suppressed: 0 bytes in 0 blocks
==12598== Rerun with --leak-check=full to see details of leaked memory
==12598==
==12598== For counts of detected and suppressed errors, rerun with: -v
==12598== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

平台信息:

浅顶软呢帽22

gcc.x86_64 5.1.1-4.fc22

valgrind.x86_64 1:3.10.1-13.fc22

codeblocks.x86_64 13.12-14.fc22

最佳答案

这是一个已知的GCC 5.1错误,而不是valgrind错误。

详细信息在这里:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=64535

可能的解决方法:
将GCC降级到较早的版本,或等待Valgrind更新此错误的修复程序。两种解决方案均由各自的社区进行开发。

10-07 19:46
查看更多