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 42 43 44 45 46 47 48 49 50 51 52 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include "clog.h"
char* repeat(char char_to_repeat, int num_times_to_repeat) { // returns memory on HEAP
int num_bytes_to_allocate = num_times_to_repeat + 1; // include space for '\0'
// NAMING TIP
// ∙ Use ▒_bytes to include the number of bytes including '\0'.
// ∙ Use ▒_chars to include the number of characters that would be printed,
// excluding the '\0'
// ∙ Names like str_size can be ambiguous and lead to bugs.
// Alocate a new string sufficient for 'num_times_to_repeat' chars and
// assign the address of the first character to 'ch_repeated_str'.
char* ch_repeated_str = malloc(num_bytes_to_allocate * sizeof(*ch_repeated_str));
for(int i = 0; i < num_times_to_repeat; i++) {
ch_repeated_str[i] = char_to_repeat; // copy one character
}
ch_repeated_str[num_times_to_repeat] = '\0'; // Write null terminator at end of string
return ch_repeated_str;
}
int main(int argc, char* argv[]) {
char* s = repeat('*', 5); // 1st call to malloc(…)
log_str(s);
free(s);
// IMPORANT: Call free(…) on every block that was allocated by malloc(…).
// └─ Corollary: Number of calls to malloc(…) should equal number of calls to free(…).
s = repeat('3', 3); // 2nd call to malloc(…) -- WARNING: not freed
log_str(s);
free(s);
s = repeat('4', 4); // 3rd call to malloc(…) -- WARNING: not freed
log_str(s);
free(s);
s = repeat('5', 5); // 4th call to malloc(…) -- WARNING: not freed
log_str(s);
free(s);
// WARNING: We are missing three calls to free(…).
return EXIT_SUCCESS;
}
// Autocomplete: Ctrl-P
/*
*/
/* 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.