From 4e658a71d7ffe214cd6a542a656d046619de643f Mon Sep 17 00:00:00 2001 From: Raghav Somasundaram PL Date: Wed, 3 Dec 2025 19:48:32 +0530 Subject: [PATCH] docs: clarify undefined behavior in pointer semantics example (fixes #182) Add detailed comments explaining that the C code example contains undefined behavior when returning a pointer to a local variable. This example is intentionally shown to demonstrate how Go differs from C in memory management - Go handles this safely while C results in undefined behavior. This resolves the misleading nature of the slide example and helps students understand the key differences between C and Go's approach to memory and pointers. --- lesson2/25_B_return_pointer.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/lesson2/25_B_return_pointer.c b/lesson2/25_B_return_pointer.c index cb24896..29452c4 100644 --- a/lesson2/25_B_return_pointer.c +++ b/lesson2/25_B_return_pointer.c @@ -1,10 +1,19 @@ #include +// WARNING: The get_pointer() function below contains UNDEFINED BEHAVIOR in C. +// It returns a pointer to a local variable that is destroyed when the function exits. +// This example is intentionally shown to demonstrate how Go differs from C: +// Go handles this safely using automatic memory management, +// while C results in undefined behavior if the pointer is dereferenced. + int* get_pointer(void) { int i = 42; return &i; } +// Note: Running this program may appear to work on some systems due to +// undefined behavior, but it can crash or produce garbage output. + int main(void) { int *p = get_pointer(); printf("%p\n", p);