valgrind

closed account (Nwb4iNh0)
What will valgrind --leak-check=yes complain about in this
program?

Anyone describe the steps to carryout the procedure to use valgrind to find memory leaks ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
#include <stdio.h>
#include <stdlib.h>
  
int main(void) {
  int x = 3;
  int *y = malloc(100);
  printf("x is at : %p\n", &x);
  printf("y is at : %p\n", y);
  x = y[1000];
  printf("x is : %d\n", x);
  return 0;
}

Vaalgrind is going to complain that y is never freed.

Also, you have an out of bounds reference at line 10.
At line 7, you're allocating 100 bytes, not 100 ints.
It'll complain that you used malloc to allocate 100... bytes? Which is going to be 25 integers. And then you didn't release it at any point before the program ended.

Look how to use Malloc:

https://www.guru99.com/malloc-in-c-example.html

y[1000] doesn't exist, you've gone over 900 elements beyond what you have.

You're missing free(y), see how to use it:

https://www.codingunit.com/c-tutorial-the-functions-malloc-and-free



Also, beware you're coding in C, not C++ - which has much better alternatives.
¿don't you have a freaking computer where you can run your little program and see the bloody output?
> Anyone describe the steps to carryout the procedure to use valgrind to find memory leaks ?

Compile your program with -g to include debugging information so that Memcheck's error messages include exact line numbers. Using -O0 is also a good idea

If you normally run your program like this: myprog arg1 arg2
Use this command line: valgrind --leak-check=yes myprog arg1 arg2
https://valgrind.org/docs/manual/quick-start.html
Topic archived. No new replies allowed.