LearnFrenzy
Sign in Take a free test

Pointers and Dynamic Memory · Find the Error · Question 7

Error: delete applied to a reference Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#include <iostream>

int main() {
    int& r = *new int(5);
    std::cout << r << '\n';
    delete r;
    return 0;
}
  • A new cannot create ints
  • B delete needs a pointer; r is an int (a reference), so it must be delete &r – better, keep the pointer or use a smart pointer Correct
  • C r must be const
  • D The value 5 is not allowed
Correct Answer: Option B

Binding heap objects to references hides ownership and invites leaks. Store the pointer (ideally std::unique_ptr<int>).

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.

Search LearnFrenzy

Esc

Quick links