OA. free
Free
MathWorks Core Computer Science Core Computer Science Medium

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

Choose 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:

  1. inc(10) is called: local variable a is created on the stack, incremented to 11.
  2. Function returns &a—the address of the local variable.
  3. When inc() returns, a goes out of scope and its memory is reclaimed/no longer guaranteed to be valid.
  4. In main(), *val dereferences a dangling pointer (points to freed/invalid stack memory).
  5. Accessing this memory at runtime causes undefined behavior: typically a segmentation fault or runtime error.
  6. The code compiles without error because the syntax is valid, but execution fails due to illegal memory access.