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

/**
 * Malloc a string
 * Fill hte string with the passed character, repeated the number
 * of times
 */
char* repeat_character(char char_to_repeat, int num_times_to_repeat) {
    // possible bug: not allocating enough space for a string
    //               need the null terminator
    // possible bug: using sizeof(output_str), allocates 8x as much space
    char* output_str = malloc((num_times_to_repeat + 1)
            * sizeof(*output_str));
    // sizeof(*output_str) == sizeof(char) == 1 byte
    // sizeof(output_str) == sizeof(char*) == 8 bytes
    //char** array_of_strings = malloc(sizeof(*array_of_strings));
    for (int i = 0; i < num_times_to_repeat; i++) {
        output_str[i] = char_to_repeat;
    }
    // possible bug: forgetting to add the null terminator to the string
    output_str[num_times_to_repeat] = '\0';
    // possible bug: cannot free an address then return the freed address
    return output_str;
}

int main(int argc, char* argv[]) {
    char* f_string = repeat_character('f', 5);
    // possible bug: freeing f_string before we print it
    printf("5 f's %s\n", f_string);
    free(f_string); 
    
    char* q_string = repeat_character('q', 7);
    printf("7 q's %s\n", q_string);
    // possible bug: double free if we try to free f_string again
    free(q_string);
    return EXIT_SUCCESS;
}
/* 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.