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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include "clog.h"
// GOOD VERSION
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: Did not allocate enough memory to accomodate the '\0' (null terminator)
// FIXED: ↓
int num_bytes_to_allocate = num_times_to_repeat + 1; // +1 for '\0'
char* char_repeated_str = malloc(num_bytes_to_allocate * sizeof(*char_repeated_str));
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: Forgot to free(…).
// FIXED: ↓
free(s);
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.