Skip to content

Commit af84b82

Browse files
committed
Add UB warning before int_ptr.cpp example in Ch 30 / 00.pointers.ipynb
The original example dereferences `*(p + 1)` and `*(p + 2)` past a single `int i`, which is undefined behavior. The output values shown in the notebook happen to read adjacent stack memory on most systems, which is what makes the demonstration useful — but students need to know this is incidental, not a pattern to rely on. This commit adds a markdown warning cell immediately before the code block to make the UB explicit. The deeper refactor (switch to an actual `int arr[3]` so the dereferences become valid) remains open under #75 as an Option-1 improvement, since it would also require updating the dependent cells (sample output, memory map). Refs #75
1 parent 58d1a82 commit af84b82

1 file changed

Lines changed: 14 additions & 1 deletion

File tree

30.pointers-and-memory-management/00.pointers.ipynb

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,19 @@
178178
"\n"
179179
]
180180
},
181+
{
182+
"cell_type": "markdown",
183+
"metadata": {},
184+
"source": [
185+
"> ⚠️ **Note on `*(p + 1)` and `*(p + 2)` below**\n",
186+
">\n",
187+
"> The expressions `*(p + 1)` and `*(p + 2)` in the example *dereference* memory past the single `int i`. Computing `p + 1` as an address is permitted by the standard, but **dereferencing it when `p` does not point into an array is undefined behavior** — the C++ standard makes no guarantee about what the value will be, or whether the read will succeed at all.\n",
188+
">\n",
189+
"> The output happens to show parts of adjacent stack memory on most systems (often `&p` itself, split across cells), which is what makes this a useful demonstration of stack layout *if you understand the caveat*. Real programs should not rely on this.\n",
190+
">\n",
191+
"> A cleaner version of this example would use an actual array (e.g., `int arr[3] = {0, 1, 2}; int *p = arr;`), so `*(p + 1)` and `*(p + 2)` become valid accesses to `arr[1]` and `arr[2]`. See [#75](https://github.com/kangwonlee/2018pycpp/issues/75) for the deeper refactor.\n"
192+
]
193+
},
181194
{
182195
"cell_type": "code",
183196
"execution_count": null,
@@ -1154,4 +1167,4 @@
11541167
},
11551168
"nbformat": 4,
11561169
"nbformat_minor": 2
1157-
}
1170+
}

0 commit comments

Comments
 (0)