LearnFrenzy
Sign in Take a free test

Pointers · Find the Error · Question 2

Wild pointer: writing through an uninitialised pointer in C Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

The program below has a problem. Which statement correctly describes it?

main.c
#include <stdio.h>

int main(void) {
    int *p;
    *p = 25;
    printf("%d\n", *p);
    return 0;
}
  • A int *p; – a pointer cannot be declared without a value
  • B *p = 25; – p was never given an address, so this writes to a random location Correct
  • C printf should print p, not *p
  • D There is no error; it prints 25
Correct Answer: Option B

Declaring int *p; is legal, but p holds garbage – a wild pointer. *p = 25 writes to an unknown address: undefined behaviour, often a crash. Point it at real memory first, e.g. int n; int *p = &n;.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Popular