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

// BUGGY -- This version has 4 known flaws:
// ∙ Does not write '\0'.
// ∙ Does not allocate space for '\0'.
// ∙ printf(…) (via log_str(…)) tries to access past the end of the buffer (block).
// ∙ Memory leak: In main(…), s is not freed.


char* repeat(char char_to_repeat, int num_times_to_repeat) {
    char* char_repeated_str = malloc(num_times_to_repeat * sizeof(*char_repeated_str));
    // BUG!!!
    for(int i = 0; i < num_times_to_repeat; i++) {
        char_repeated_str[i] = char_to_repeat;
    }
    // BUG!!!
    return char_repeated_str;
}

int main(int argc, char* argv[]) {
    char* s = repeat('*', 5);
    log_str(s);  //  expands to code that calls printf(…) or fprintf(…)
    // BUG!!!
    return EXIT_SUCCESS;
}
/*
$ valgrind ./t
==23056== Memcheck, a memory error detector
==23056== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==23056== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==23056== Command: ./t
==23056==
==23056== Invalid read of size 1
==23056==    at 0x4E84079: vfprintf (vfprintf.c:1635)
==23056==    by 0x4E8A446: fprintf (fprintf.c:32)
==23056==    by 0x40066A: main (t.c:20)
==23056==  Address 0x5205045 is 0 bytes after a block of size 5 alloc'd
==23056==    at 0x4C29F73: malloc (vg_replace_malloc.c:309)
==23056==    by 0x4005F1: repeat (t.c:9)
==23056==    by 0x400641: main (t.c:19)
==23056==
s == "*****"
==23056==
==23056== HEAP SUMMARY:
==23056==     in use at exit: 5 bytes in 1 blocks
==23056==   total heap usage: 1 allocs, 0 frees, 5 bytes allocated
==23056==
==23056== 5 bytes in 1 blocks are definitely lost in loss record 1 of 1
==23056==    at 0x4C29F73: malloc (vg_replace_malloc.c:309)
==23056==    by 0x4005F1: repeat (t.c:9)
==23056==    by 0x400641: main (t.c:19)
==23056==
==23056== LEAK SUMMARY:
==23056==    definitely lost: 5 bytes in 1 blocks
==23056==    indirectly lost: 0 bytes in 0 blocks
==23056==      possibly lost: 0 bytes in 0 blocks
==23056==    still reachable: 0 bytes in 0 blocks
==23056==         suppressed: 0 bytes in 0 blocks
==23056==
==23056== For lists of detected and suppressed errors, rerun with: -s
==23056== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
 */
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

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