From be78fa799d39dbf65d77baab2da62836ebce3f89 Mon Sep 17 00:00:00 2001 From: Edson Brandi Date: Fri, 7 Nov 2025 22:57:09 +0000 Subject: [PATCH] Fix null terminator demonstration to show undefined behavior The previous example wasn't reliably demonstrating the danger of missing null terminators because the stack happened to contain a '\0' byte immediately after the array, making the broken code appear to work. Added memset() to fill the stack with non-zero values before declaring the unterminated array. This ensures the broken example actually exhibits undefined behavior by reading past the array boundary, making the lesson about null terminators clear and visible. Changes: - Added garbage array filled with 'Z' characters using memset() - This forces printf() to read past the broken array until finding '\0' - Readers now see actual garbage output demonstrating why null terminators are required in C strings --- content/chapters/part1/chapter-04.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/content/chapters/part1/chapter-04.md b/content/chapters/part1/chapter-04.md index a1ebf43..62ca580 100644 --- a/content/chapters/part1/chapter-04.md +++ b/content/chapters/part1/chapter-04.md @@ -3730,8 +3730,13 @@ To illustrate the subtlety of this class of bug, try the following small program ```c #include +#include int main() { + // Fill stack with non-zero garbage + char garbage[100]; + memset(garbage, 'Z', sizeof(garbage)); + // Deliberately forget the null terminator char broken[5] = {'B', 'S', 'D', '!', 'X'};