Common Errors
Explore common pointer errors related to returning pointers to local and static variables in C. Learn why returning pointers to local variables causes undefined behavior and why pointers to static variables, though safer, remain bad practice. This lesson helps you understand stack memory behavior and how to write more reliable pointer code.
We'll cover the following...
Pointer to local variables
Let’s explore a common problem found in pointer-intensive code using the example below:
We changed doubleNum to return a pointer to the result instead of returning the result directly.
In line 5, y contains the result of the computation. Then, on lines 7 and 8, we create a pointer to y and return it.
Inside main, at line 15, we dereference the pointer to get the value.
Run the code and see that the output is 10, which appears to be correct. But is it?
The y ...