1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
char* repeat_char(char ch, size_t num_times) {
    char* s = malloc(sizeof(*s) * (num_times + 1));
    for(size_t i = 0; i < num_times; i++) {
        s[i] = ch;
    }
    s[num_times] = '\0';
    return s;
}

void print_string(char* s) {
    for(int i = 0; s[i] != '\0'; i++) {  // ▶▶▶ !!! INVALID READ … free'd !!! ◀◀◀
        fputc(s[i], stdout);             // ▶▶▶ !!! INVALID READ … free'd !!! ◀◀◀
    }
}

int main(int argc, char* argv[]) {
    char* s = repeat_char('@', 3);
    free(s);   // ▶ Whoops... should free(…) only after done using buffer at s ◀
    print_string(s);
    return EXIT_SUCCESS;
}

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