ProgrammingHardWipro · Cognizant pattern

What happens?

What happens?
struct Node {
    int data;
    struct Node *next;
};
struct Node *createNode(int val) {
    struct Node n;
    n.data = val;
    n.next = NULL;
    return &n;
}
int main(void) {
    struct Node *p = createNode(5);
    printf("%d", p->data);
}
  1. A. Compilation error: cannot return the address of a local struct
  2. B. 5
  3. C. Undefined behaviour: n is a local variable with automatic storage; returning &n gives main a dangling pointer once createNode returns
  4. D. 0

Correct answer: C. Undefined behaviour: n is a local variable with automatic storage; returning &n gives main a dangling pointer once createNode returns

n has automatic storage duration tied to createNode's stack frame; once the function returns, that memory is no longer reserved for n, and p->data dereferences a dangling pointer — classic undefined behaviour (you'd need malloc to safely return a heap-allocated node instead).

More C Programming questions

Exams that ask this topic