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
This commit is contained in:
Edson Brandi 2025-11-07 22:57:09 +00:00
parent 87e7742451
commit be78fa799d

View file

@ -3730,8 +3730,13 @@ To illustrate the subtlety of this class of bug, try the following small program
```c ```c
#include <stdio.h> #include <stdio.h>
#include <string.h>
int main() { int main() {
// Fill stack with non-zero garbage
char garbage[100];
memset(garbage, 'Z', sizeof(garbage));
// Deliberately forget the null terminator // Deliberately forget the null terminator
char broken[5] = {'B', 'S', 'D', '!', 'X'}; char broken[5] = {'B', 'S', 'D', '!', 'X'};