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

// BUGGY -- This version has 3 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).

char* repeat(char char_to_repeat, int num_times_to_repeat) { // returns memory on HEAP
    // 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_times_to_repeat * sizeof(*ch_repeated_str));
    for(int i = 0; i < num_times_to_repeat; i++) {
        ch_repeated_str[i] = char_to_repeat;  // copy one character
    }
    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
/* 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.