What is the output of the following snippet of code?
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
What is the output of the following snippet of code?
#include <stdio.h>
int* inc(int val)
{
int a = val;
a++;
return &a;
}
int main(void)
{
int a = 10;
int *val = inc(a);
printf("\n Incremented value is equal to [%d] \n", *val);
return 0;
}
Pick ONE option
Show answer & explanation
Answer: C. Runtime Error
The function inc() returns a pointer to a local variable a, which ceases to exist when the function returns. Dereferencing this dangling pointer in main() results in undefined behavior—typically a runtime error or garbage value. While the code compiles successfully, accessing the invalid memory address at runtime causes a crash or unpredictable output.
Step-by-step Derivation:
Step-by-step analysis:
inc(10)is called: local variableais created on the stack, incremented to 11.- Function returns
&a—the address of the local variable. - When
inc()returns,agoes out of scope and its memory is reclaimed/no longer guaranteed to be valid. - In
main(),*valdereferences a dangling pointer (points to freed/invalid stack memory). - Accessing this memory at runtime causes undefined behavior: typically a segmentation fault or runtime error.
- The code compiles without error because the syntax is valid, but execution fails due to illegal memory access.