Machine-translated by Google. Questions are authored in English.
Top

Discussion

What is the output of this C code?

#include <stdio.h>
    int *f();
    int main()
    {
        int *p = f();
        printf("%d\n", *p);
    }
    int *f()
    {
        int *j = (int*)malloc(sizeof(int));
        *j = 10;
        return j;
    }

 

  • A.10
  • B.Compile time error
  • C.Segmentation fault/runtime crash since pointer to local variable is returned
  • D.Undefined behaviour

Answer: A

Correct answer: 10

The storage is obtained from malloc, so it lives on the heap and its lifetime is independent of the function that allocated it. Returning the pointer is therefore legitimate, and the caller reads 10.

The contrast with returning the address of a local is the whole point: an automatic variable's lifetime ends when the function returns, leaving a dangling pointer. The only fault here is the missing free, which leaks the block - a leak rather than an error in the value printed.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.