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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

// MEMORY LEAK
//
// To avoid:  Make sure you call free(…) exactly once for every time you call malloc(…).
// You must call free(…) with the address of the buffer you want to free.
//
// Read the specification carefully.  Sometimes, it will say, "Caller is responsible for freeing
// the new string." or something similar.

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

    printf("s == \"%s\"\n", s);  // BAD!!!

    // OOPS!!! Forgot to free.
    
    return EXIT_SUCCESS;
}
/*
==36787== Memcheck, a memory error detector
==36787== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==36787== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==36787== Command: ./c
==36787==
s == "ab"
==36787==
==36787== HEAP SUMMARY:
==36787==     in use at exit: 3 bytes in 1 blocks
                              ▲          ▲
                              │          number of blocks (buffers allocated by malloc(…)) leaked (not free'd)

                              number of bytes that are leaked (malloc'd but not free'd)
==36787==   total heap usage: 1 allocs, 0 frees, 3 bytes allocated
                              ▲         ▲        ▲
                              │         │        Sum of the number of byte allocated in every call to malloc(…)
                              │         │        
                              │         number of times free(…) was called

                              number of times malloc was called
==36787==
==36787== 3 bytes in 1 blocks are definitely lost in loss record 1 of 1
==36787==    at 0x4C29F73: malloc (vg_replace_malloc.c:309)
==36787==    by 0x40059D: main (c.c:9)
==36787==
==36787== LEAK SUMMARY:
==36787==    definitely lost: 3 bytes in 1 blocks
==36787==    indirectly lost: 0 bytes in 0 blocks
==36787==      possibly lost: 0 bytes in 0 blocks
==36787==    still reachable: 0 bytes in 0 blocks
==36787==         suppressed: 0 bytes in 0 blocks
           // For now, don't worry about the distinction between leak types.
==36787==
==36787== For lists of detected and suppressed errors, rerun with: -s
==36787== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
*/
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

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