1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <stdio.h>
#include <stdlib.h>

/* This snippet was used as part of an exercise in drawing the contents
 * of memory.  The answer is at the bottom.  The form we used is here:
 * https://engineering.purdue.edu/ece264/17au/download/memory_form.pdf
 */

int main(int argc, char* argv[]) {
    int num_chars = 3;
    char* s = malloc(sizeof(*s) * num_chars);
    
    s[0] = 'Y';
    s[1] = 'o';
    s[2] = '\0';

    printf("%s\n", s);
    free(s);
    int* a_n = &num_chars;

    a_n = malloc(sizeof(*a_n) * 3);
    a_n[0] = 10;
    a_n[1] = 11;
    a_n[2] = 12;

    /* LEAK!!!  The allocation block referenced by a_n was never freed.
     */

    return EXIT_SUCCESS;
}
/*
 * You should have…
 *
 * ∙ 3 local variables:  num_chars  (address=220  type=int    value=3)
 *                       s          (address=224  type=char*  value=400)
 *                       a_n        (address=232  type=int*   value=403)
 *
 *   The next local variable would be at address 240.
 *
 * ∙ 2 arguments:        argc       (address=200  type=int    value=1)
 *                       argv       (address=204  type=char** value not shown)
 *
 * ∙ 2 heap allocation:   3 bytes   (address=400  freed       value={'Y', 'o', '\0'})
 *                       12 bytes   (address=403  NOT freed   value={10, 11, 12})
 *
 *   The heap allocation would be at address 415.
 *
 * The second heap allocation block should show a lock symbol, since it was never freed.
 *
 *
 * VALGRIND OUTPUT:
 * 
 * ==18691== HEAP SUMMARY:
 * ==18691==     in use at exit: 12 bytes in 1 blocks
 * ==18691==   total heap usage: 2 allocs, 1 frees, 15 bytes allocated
 * ==18691==
 * ==18691== 12 bytes in 1 blocks are definitely lost in loss record 1 of 1
 * ==18691==    at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
 * ==18691==    by 0x400663: main (memory_exercise.c:21)
 * ==18691==
 * ==18691== LEAK SUMMARY:
 * ==18691==    definitely lost: 12 bytes in 1 blocks
 * ==18691==    indirectly lost: 0 bytes in 0 blocks
 * ==18691==      possibly lost: 0 bytes in 0 blocks
 * ==18691==    still reachable: 0 bytes in 0 blocks
 * ==18691==         suppressed: 0 bytes in 0 blocks
 * 
 */

© Copyright 2017 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.