heap_checker.cc 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // Copyright (c) 2013-2021 Winlin
  3. //
  4. // SPDX-License-Identifier: MIT
  5. //
  6. /**
  7. @see: https://gperftools.github.io/gperftools/heap_checker.html
  8. config srs with gperf(to make gperftools):
  9. ./configure --gperf=on --jobs=3
  10. set the pprof path if not set:
  11. export PPROF_PATH=`pwd`/../../../objs/pprof
  12. to check mem leak:
  13. make && env HEAPCHECK=normal ./heap_checker
  14. */
  15. #include <stdio.h>
  16. #include <unistd.h>
  17. #include <signal.h>
  18. #include <stdlib.h>
  19. #include <gperftools/profiler.h>
  20. void explicit_leak_imp() {
  21. printf("func leak: do something...\n");
  22. for (int i = 0; i < 1024; ++i) {
  23. char* p = new char[1024];
  24. }
  25. printf("func leak: memory leaked\n");
  26. }
  27. void explicit_leak() {
  28. explicit_leak_imp();
  29. }
  30. char* pglobal = NULL;
  31. void global_leak_imp() {
  32. printf("global leak: do something...\n");
  33. for (int i = 0; i < 1024; ++i) {
  34. pglobal = new char[189];
  35. }
  36. printf("global leak: memory leaked\n");
  37. }
  38. void global_leak() {
  39. global_leak_imp();
  40. }
  41. bool loop = true;
  42. void handler(int sig) {
  43. // we must use signal to notice the main thread to exit normally.
  44. if (sig == SIGINT) {
  45. loop = false;
  46. }
  47. }
  48. int main(int argc, char** argv) {
  49. signal(SIGINT, handler);
  50. global_leak();
  51. printf("press CTRL+C if you want to abort the program.\n");
  52. sleep(3);
  53. if (!loop) {
  54. return 0;
  55. }
  56. explicit_leak();
  57. printf("press CTRL+C if you want to abort the program.\n");
  58. sleep(3);
  59. if (!loop) {
  60. return 0;
  61. }
  62. return 0;
  63. }