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 53 54 55 56 57 58 59 60 61 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include "clog.h"
// BUGGY -- This version has 1 known flaw:
// ∙ 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: 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!!!
return EXIT_SUCCESS;
}
/*
$ valgrind ./v
==40910== Memcheck, a memory error detector
==40910== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==40910== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==40910== Command: ./v
==40910==
s == "*****"
==40910==
==40910== HEAP SUMMARY:
==40910== in use at exit: 6 bytes in 1 blocks
==40910== total heap usage: 1 allocs, 0 frees, 6 bytes allocated
==40910==
==40910== 6 bytes in 1 blocks are definitely lost in loss record 1 of 1
==40910== at 0x4C29F73: malloc (vg_replace_malloc.c:309)
==40910== by 0x4005FA: repeat (v.c:14)
==40910== by 0x40065A: main (v.c:26)
==40910==
==40910== LEAK SUMMARY:
==40910== definitely lost: 6 bytes in 1 blocks
==40910== indirectly lost: 0 bytes in 0 blocks
==40910== possibly lost: 0 bytes in 0 blocks
==40910== still reachable: 0 bytes in 0 blocks
==40910== suppressed: 0 bytes in 0 blocks
==40910==
==40910== For lists of detected and suppressed errors, rerun with: -s
==40910== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
*/
/* 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.