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

// GOOD -- This version has no known flaws.

char* repeat(char char_to_repeat, int num_times_to_repeat) { // returns memory on HEAP
    int num_bytes_to_allocate = num_times_to_repeat + 1;  // include space for '\0'
    // NAMING TIP: ∙ Use ▒_bytes to include the number of bytes including '\0'.
    //             ∙ Use ▒_chars to include the number of characters that would be printed,
    //               excluding the '\0'
    //             ∙ Names like str_size can be ambiguous and lead to bugs.

    // Alocate a new string sufficient for 'num_times_to_repeat' chars and
    // assign the address of the first character to 'ch_repeated_str'.
    char* ch_repeated_str = malloc(num_bytes_to_allocate * sizeof(*ch_repeated_str));
    for(int i = 0; i < num_times_to_repeat; i++) {
        ch_repeated_str[i] = char_to_repeat;  // copy one character
    }
    ch_repeated_str[num_times_to_repeat] = '\0';  // Write null terminator at end of string

    return ch_repeated_str;
}

int main(int argc, char* argv[]) {
    
    char* s = repeat('*', 5);
    log_str(s);
    free(s);

    // IMPORANT: Call free(…) on every block that was allocated by malloc(…).
    //  └─ Corollary: Number of calls to malloc(…) should equal number of calls to free(…).
    
    return EXIT_SUCCESS;
}

// Autocomplete:  Ctrl-P

/*
$ valgrind ./e.repeat
==32140== Memcheck, a memory error detector
==32140== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==32140== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==32140== Command: ./e.repeat
==32140==
s == "*****"
==32140==
==32140== HEAP SUMMARY:
==32140==     in use at exit: 0 bytes in 0 blocks
==32140==   total heap usage: 1 allocs, 1 frees, 6 bytes allocated
==32140==
==32140== All heap blocks were freed -- no leaks are possible
==32140==
==32140== For lists of detected and suppressed errors, rerun with: -s
==32140== ERROR SUMMARY: 0 errors from 0 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.