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);
}- A. Compilation error: cannot return the address of a local struct
- B. 5
- C. Undefined behaviour: n is a local variable with automatic storage; returning &n gives main a dangling pointer once createNode returns
- 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
- What is printed? c void outerFunc(void) { int x = 10; { int y = 20; printf("%d %d ", x, y); } // printf("%d", y); // line X } int…
- What is printed? c int idgenerator(void) { static int nextid = 100; return nextid++; } int main(void) { int a = idgenerator(); int b =…
- What is printed? c int applyTwice(int (f)(int), int x) { return f(f(x)); } int square(int x) { return x x; } int main(void) { printf("%d"…
- What is printed? c int main(void) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (j == i) continue; printf("%d%d ", i…
- What is printed? c int main(void) { int x = 2; switch (x) { case 1: case 2: case 3: printf("low "); break; case 4: case 5: printf("high…
- What is printed? c int main(void) { int arr[5] = {1, 2, 3, 4, 5}; int sum = 0; for (int i = 0; i < 5; i += 2) { sum += arr[i]; }…