Debugging Dynamic Memory Usage Errors Using HP WDB (766161-001, March 2014)

Example 27 Memory debugging using RTC APIs
$ cat n sample_program.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <rtcapi.h> 5
6 void call_rtc_api_here();
7
8 main()
9 {
10 int i, *arr[100];
11
12 printf ("\nHeap checking using RTC APIs \n");
13
14 /* Enable the program to detect leaks, check heap and check free
15 in the program using RTC APIs */
16 rtc_enable (RTC_CHECK_LEAKS | RTC_CHECK_HEAP | RTC_CHECK_FREE);
17
18 for (i=0; i < 100; i++)
19 arr[i] = (int *) malloc (50);
20
21 /* Leaks due to overwriting pointers in arr array. */
22 arr[0] = (int *) malloc (100);
23 arr[1] = (int *) malloc (100);
24 arr[2] = (int *) malloc (100);
25
26 /* Leaks report goes to STDOUT */
27 call_rtc_api_here();
28
29 /* Leaks report printed to rtc_report.rep file. */
30 rtc_logfile("/tmp/rtc_report.rep", RTC_LOG_SET);
31
32 /* Now onwards all types of report printed to /tmp/rtc_report.rep file. */
33 call_rtc_api_here();
34
35 /* This should not report since bounds checking is not enabled */
36 rtc_heap_corruption();
37
38 /* Disables printing leaks to rtc_report.rep and redirects it to STDOUT. */
39 rtc_logfile("/tmp/rtc_report.rep", RTC_LOG_UNSET);
40
41 char * charptr = (char *) calloc (10, 1);
42 arr[3] = (int *) malloc (100);
43 arr[4] = (int *) malloc (100);
44 arr[5] = (int *) malloc (100);
45
46 free (charptr);
47 charptr = NULL;
48
49 /* New leaks report printed to STDOUT */
50 rtc_leaks (RTC_LEAK_NEW);
51
52 rtc_disable (RTC_CHECK_LEAKS);
53
54 /* Do not expect leaks report after disabling. But can get heap report. */
55 call_rtc_api_here();
56
57 exit(0);
58 }
59
60 void call_rtc_api_here (void)
61 {
62 rtc_leaks(RTC_LEAK_ALL);
63 rtc_heap();
64 }
65
90