Debugging Dynamic Memory Usage Errors Using HP WDB v6.3 (5900-2181, August 2012)
Sample Test Case to Detect Point of Memory Leak
The “Steps to Detect Point of Memory Leak” (page 69) are represented through a sample test case.
The sample test case is provided as shown below:
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4
5 /* Allocate memory and return it to the caller */
6 void *allocateMemory(size_t n)
7 {
8 void *memBlock = NULL;
9 printf("Allocating memory of size %d\n", n);
10
11 memBlock = malloc(n);
12 if (!memBlock)
13 {
14 printf("No memory available, aborting...\n");
15 abort ();
16 }
17
18 return memBlock;
19 }
20
21 /* Create a header string and return to the caller */
22 char *createHeader()
23 {
24 char *headerString = (char *) allocateMemory(20);
25 strcpy (headerString, "Header : My string ");
26 return headerString;
27 }
28
29 /* Create a string with header and input. Return to the caller */
30 char *createString(char *input, int n)
31 {
32 #define MAXBADINPUT (10)
33
34 char *hdrString, *myString;
35 int inputLength = strlen(input);
36 static int badInput;
37 hdrString = createHeader();
38 /* Input length too small ? return back from here */
39 if (n < inputLength + 20)
40 {
41 hdrString = NULL;
42 printf("Too small size for a string, not allocating\n");
43 badInput++;
44 printf("Number of badInput is %d\n", badInput);
45 if (badInput > MAXBADINPUT)
46 {
47 printf("Too many bad inputs.. aborting\n");
48 abort();
49 }
50 return NULL;
51 }
52
53 /* Allocate the string, copy the header to it */
54 myString = (char *)allocateMemory(n);
55 strcpy(myString, hdrString);
56 free(hdrString);
57
58 /* Copy the input to the string after header and return */
59 strcpy(myString+20, input);
60 return (myString);
70