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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include "clog.h"
// BUGGY -- This version has 1 known flaw:
// ∙ In main(…), the memory at (address) s is freed twice ("double free"). In other words,
// free(s) is called twice.
char* repeat(char char_to_repeat, int num_times_to_repeat) {
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;
}
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);
free(s);
free(s); // BUG!!! double free
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.