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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
/**
* Malloc a string
* Fill hte string with the passed character, repeated the number
* of times
*/
char* repeat_character(char char_to_repeat, int num_times_to_repeat) {
// possible bug: losing the original address during iteration
// best fix: store a copy of the original address
char* const output_str = malloc((num_times_to_repeat + 1)
* sizeof(*output_str));
char* iterate_str = output_str;
for (int i = 0; i < num_times_to_repeat; i++) {
*iterate_str = char_to_repeat;
iterate_str += 1;
}
*iterate_str = '\0';
// this could lead to off by one errors
// output_str -= num_times_to_repeat;
return output_str;
}
int main(int argc, char* argv[]) {
char* f_string = repeat_character('f', 5);
// possible bug: freeing f_string before we print it
printf("5 f's %s\n", f_string);
free(f_string);
char* q_string = repeat_character('q', 7);
printf("7 q's %s\n", q_string);
// possible bug: double free if we try to free f_string again
free(q_string);
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.