text 使用'valgrind'来检查内存泄漏

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text 使用'valgrind'来检查内存泄漏相关的知识,希望对你有一定的参考价值。

'valgrind' is a command in cs50 IDE that checks if there's any memory leaks in your program. It will find out errors like:

1. If you touched memory block that you are not supposed to touch. Usually you'll get a 'segmentation fault' for it, but sometimes you might get lucky and 'malloc()' allocated a few more blocks than you coded so you don't get a segmentation fault. But 'valgrind' will be able to find faults like that.

2. If you forget to free up memory that you no longer use.

To use 'valgrind', you need to finish compiling your program first, and then just add 'valgrind' in front of './program_name':

valgrind ./memory

After you run it, lots of error messages might come up and hard to understand. You can add "help50" before that to help interprete it more and make it easy to understand:

help50 valgrind ./memory

For example, here's a simpe program called 'memory.c':

#include <stdlib.h>

void f(void)
{
    int *x = malloc(10 * sizeof(int));
    x[10] = 0;
}

int main(void)
{
    f();
    return 0;
}


So we can see that there are 2 memory problems in this code:

x[10]: we got out of bound of the allocated block.
And we didn't free memory blocks after use.

We can run after compiling:

valgrind ./memory

Lots of error messages might come up. If we don't understand, just add 'help50' before it:

help50 valgrind ./memory

Then it will be much easier to understand, and we can correct the errors.


以上是关于text 使用'valgrind'来检查内存泄漏的主要内容,如果未能解决你的问题,请参考以下文章

valgrind 使用 std::string 报告无效读取

Valgrind OpenCV

在 Valgrind 中是不是需要处理仍然可访问的内存?

valgrind mac os sierra 10.12.1

valgrind memcheck xtree 文件的工具

如何在matlab中的xlabel,ylabel,legend和text函数中使用latex