1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | char* repeat_char(char ch, size_t num_times) {
char* s = malloc(sizeof(*s) * num_times); // ▶ Whoops... didn't make room for '\0' ◀
for(size_t i = 0; i < num_times; i++) {
s[i] = ch;
}
s[num_times] = '\0'; // ▶▶▶ !!! INVALID WRITE … 0 bytes after !!! ◀◀◀
return s; // AKA "buffer overflow"
}
void print_string(char* s) {
for(int i = 0; s[i] != '\0'; i++) { // ▶▶▶ !!! INVALID READ … 0 bytes after !!! ◀◀◀
fputc(s[i], stdout); // (when s==2) AKA "buffer overread"
}
}
int main(int argc, char* argv[]) {
char* s = repeat_char('@', 3); // ⇒ "@@@"
print_string(s); // same as printf("%s", s)
free(s);
return EXIT_SUCCESS;
}
|
© Copyright 2023 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.