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

char* repeat_char(char ch, size_t num_times) {
    for(size_t i = 0; i < num_times; i++) {
        /* code */
    }
}

char* s = malloc(sizeof(*s) * s_len);
int main(int argc, char* argv[]) {
    size_t s_len = 3;  // bytes including '\0'
    char* s = malloc(sizeof(*s) * s_len);
    s[0] = 'a';
    s[1] = 'b';
    s[2] = '\0';

    free(s);

    for(int i = 0; i < s_len; i++) {
        fputc(s[i], stdout);  // BUG!!! Reading the memory after it was free'd.
        // "Invalid read of size 1" … "Address 0x5205040 is 0 bytes inside a block of size 3 free'd"
    }

    return EXIT_SUCCESS;
}

/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

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