Pointers in C++ may have potential problems if not properly used. For the following C++ code, identify the problem, briefly explain the problem, and also state Java's handling of such cases.
int *p1;
p1 = new int [1000];
p1 = new int [10];
(a) Name the problem:
(b) Brief explain what caused the problem:
(c) Does Java suffer similar problem? If yes, say so. If no, how does Java avoid such problem?
a.) The given code will lead to memory leak.
b.) Memory leak happens in this case because the variable p1 which was containing dynamic memory was written by the next statement. The memory should have been freed first before assigning memory to it again.
c.) Java does not suffer from the same problem. In java, the memory is managed automatically. It has a built-in garbage collector. It provides an efficient solution for memory leaks.
The memory leak may still happen due to some static variables of methods.
Get Answers For Free
Most questions answered within 1 hours.