How to use valgrind to check memory in Linux system

  

During the process of writing code using Linux system, there may be a problem of memory leaks. So users should learn to check memory, so how does Linux check memory? Generally use some tools, this article will introduce how to use valgrind to check memory in Linux system.

Take a look at the code:

#include "stdlib.h"

#include "stdio.h"

#include "string .h》

static void mem_leak1(void)

{

char *p = malloc(1);

}

Static void mem_leak2(void)

{

FILE *fp = fopen(“test.txt”, “w”);

}

static void mem_overrun1(void)

{

char *p = malloc(1);

*(short*)p = 2;

Free(p);

}

static void mem_overrun2(void)

{

char array[5];

strcpy (array, “hello”);

}

static void mem_double_free(void)

{

char *p = malloc(1);

free(p);

free(p);

}

static void mem_use_wild_pointer(void)

{

char *p = (void*)0x80184800;

*p = 1;

}

static void mem_free_wild_pointer(void)

{

char *p;

free(p);

}

int main()

{

mem_leak1();

mem_leak2();

mem_overrun1();

mem_overrun2();

mem_double_free();

//mem_use_wild_pointer();

mem_free_wild_pointer();

return 0;

}

Common memory problems:

1. Dynamic memory leak;

2. Resource leak, here is a file descriptor;

3. Dynamic memory out of bounds;

4. Array memory out of bounds ;

5. Dynamic memory double free;

6. Use wild pointer, that is, uninitialized pointer;

7. Release the wild pointer, that is, the uninitialized pointer;

Where the sample code is too simple, the sixth case makes Wild pointer will directly lead to crash, so in the main, there is no real sample code that call. Since valgrind can only detect the code that was executed, the sixth error condition will not be reported in a later report. However, in large projects, it is possible to use wild pointers without causing program crashes. In addition, in the above 7 cases, some cases are strictly speaking, and can actually be classified into one category. Previous12Next page Total 2 pages

Copyright © Windows knowledge All Rights Reserved