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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include "clog.h"
// BUGGY -- This version has 3 known flaws:
// ∙ Does not allocate space for '\0'.
// ∙ printf(…) (via log_str(…)) tries to access past the end of the buffer (block).
// ∙ Memory leak: In main(…), s is not freed.
char* repeat(char char_to_repeat, int num_times_to_repeat) {
char* char_repeated_str = malloc(num_times_to_repeat * sizeof(*char_repeated_str));
// BUG!!!
for(int i = 0; i < num_times_to_repeat; i++) {
char_repeated_str[i] = char_to_repeat;
}
// BUG: Forgot to write '\0' (null terminator) after the printable characters.
// FIXED: ↓ (but we still have bugs)
char_repeated_str[num_times_to_repeat] = '\0'; // VALGRIND: Invalid write of size 1.
return char_repeated_str;
}
int main(int argc, char* argv[]) {
char* s = repeat('*', 5);
log_str(s); // expands to code that calls printf(…) or fprintf(…)
// BUG!!!
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.