3

我正在尝试使用 Valgrind 在我的代码中出现免费错误后调试使用。

我的代码在尝试访问以前删除的对象时崩溃。在这种情况下,有什么方法可以查看谁使用 Valgrind 删除了对象?

我使用以下选项运行 Valgrind,但它只捕获崩溃,并显示它发生的位置。我希望获得有关对象被释放位置的详细信息:

valgrind --tool=memcheck

4

2 回答 2

6

这就是我在这些情况下使用的:

valgrind --track-origins=yes

在释放后使用的情况下,它将显示释放内存/删除对象的函数的堆栈跟踪。

请阅读 Valgrind 的手册页以了解警告,特别是有关性能的警告。如果您的问题是并发问题,较慢的 Valgrind 可能会改变程序的计时属性,并可能改变(减少或增加)遇到 bug 的概率。

--track-origins=<yes|no> [default: no]
    Controls whether Memcheck tracks the origin of uninitialised
    values. By default, it does not, which means that although it can
    tell you that an uninitialised value is being used in a dangerous
    way, it cannot tell you where the uninitialised value came from.
    This often makes it difficult to track down the root problem.

    When set to yes, Memcheck keeps track of the origins of all
    uninitialised values. Then, when an uninitialised value error is
    reported, Memcheck will try to show the origin of the value. An
    origin can be one of the following four places: a heap block, a
    stack allocation, a client request, or miscellaneous other sources
    (eg, a call to brk).

    For uninitialised values originating from a heap block, Memcheck
    shows where the block was allocated. For uninitialised values
    originating from a stack allocation, Memcheck can tell you which
    function allocated the value, but no more than that -- typically it
    shows you the source location of the opening brace of the function.
    So you should carefully check that all of the function's local
    variables are initialised properly.

    Performance overhead: origin tracking is expensive. It halves
    Memcheck's speed and increases memory use by a minimum of 100MB,
    and possibly more. Nevertheless it can drastically reduce the
    effort required to identify the root cause of uninitialised value
    errors, and so is often a programmer productivity win, despite
    running more slowly.

    Accuracy: Memcheck tracks origins quite accurately. To avoid very
    large space and time overheads, some approximations are made. It is
    possible, although unlikely, that Memcheck will report an incorrect
    origin, or not be able to identify any origin.

    Note that the combination --track-origins=yes and
    --undef-value-errors=no is nonsensical. Memcheck checks for and
    rejects this combination at startup.
于 2012-12-02T01:06:00.623 回答
1

Valgrind 已经向您展示了它的最大能力。你需要用更多的调试信息来编译你的代码——然后 valgrind 将能够向你显示更多的信息,例如文件、函数和行。

使用选项编译代码-g并使用 valgrind 重新运行。在某些编译器上,还有 -gNN调试级别。但在大多数情况下,-g就足够了。

于 2012-12-02T00:21:56.630 回答