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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include "clog.h"
// BUGGY -- This version has 4 known flaws:
// ∙ Does not write '\0'.
// ∙ Does not allocate space for '\0'.
// ∙ printf(…) (via log_str(…)) tries to access past the end of the buffer (block).
// ∙ Memory leak: In main(…), s is not freed.
// Note: "buffer" is just another term for a block of memory.
char* repeat(char char_to_repeat, int num_times_to_repeat) { // returns memory on HEAP
// WARNING: This has a BUG.
// 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_times_to_repeat * sizeof(*ch_repeated_str));
for(int i = 0; i < num_times_to_repeat; i++) {
ch_repeated_str[i] = char_to_repeat; // copy one character
}
return ch_repeated_str;
}
int main(int argc, char* argv[]) {
char* s = repeat('*', 5);
log_str(s);
// WARNING: BUG HERE, TOO.
return EXIT_SUCCESS;
}
// Autocomplete: Ctrl-P
/*
$ valgrind ./b.repeat
==40952== Memcheck, a memory error detector
==40952== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==40952== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==40952== Command: ./b.repeat
==40952==
==40952== Invalid read of size 1
==40952== at 0x4E84079: vfprintf (vfprintf.c:1635)
==40952== by 0x4E8A446: fprintf (fprintf.c:32)
==40952== by 0x40066A: main (b.repeat.c:22)
==40952== Address 0x5205045 is 0 bytes after a block of size 5 alloc'd
==40952== at 0x4C29F73: malloc (vg_replace_malloc.c:309)
==40952== by 0x4005F1: repeat (b.repeat.c:12)
==40952== by 0x400641: main (b.repeat.c:21)
==40952==
s == "*****"
==40952==
==40952== HEAP SUMMARY:
==40952== in use at exit: 5 bytes in 1 blocks
==40952== total heap usage: 1 allocs, 0 frees, 5 bytes allocated
==40952==
==40952== 5 bytes in 1 blocks are definitely lost in loss record 1 of 1
==40952== at 0x4C29F73: malloc (vg_replace_malloc.c:309)
==40952== by 0x4005F1: repeat (b.repeat.c:12)
==40952== by 0x400641: main (b.repeat.c:21)
==40952==
==40952== LEAK SUMMARY:
==40952== definitely lost: 5 bytes in 1 blocks
==40952== indirectly lost: 0 bytes in 0 blocks
==40952== possibly lost: 0 bytes in 0 blocks
==40952== still reachable: 0 bytes in 0 blocks
==40952== suppressed: 0 bytes in 0 blocks
==40952==
==40952== For lists of detected and suppressed errors, rerun with: -s
==40952== ERROR SUMMARY: 2 errors from 2 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.