This was a question in one of my books (with no answer attached to it), that I've been thinking about for a few days now. Is the answer simply that the C++ code will eventually crash because it is creating a garbage memory cell after each iteration?
Consider the following Java and C++ code fragments, parts of two versions of a GUI based application which collects user preferences and use them to assemble a command and its parameters. The method/function getUserCommandSpecification() returns a string representing the command code and its parameters. The returned string is used to build the required command which is then executed.
Assume the following:
(i) After the creation in the while loop of the Command object (referred by cmd in Java case or pointed by cmd in C++ case), the reference / pointer cmd to the generated object is no more referenced or used.
(ii) The application also defines a class Command along with its method/function execute().
a. Which of the two code versions, detailed below, will eventually crash.
b. Explain why a program version crashes while the other one is not crashing.
Java code
...
while (true) {
String commandSpecification = getUserCommandSpecification();
Command cmd = new Command(commandSpecification);
cmd.execute();
}
...
C++ code
...
while (true) {
string commandSpecification = getUserCommandSpecification();
Command* cmd = new Command(commandSpecification);
cmd -> execute();
}
...
An infinite loop is a piece of code that keeps running forever as the terminating condition is never reached. An infinite loop can crash your program or browser and freeze your computer.
Infinite loops occur when loops have no exit condition - no way to stop - so when the program is run it loops forever with no break, causing the browser to crash. This happens most often with while loops, but any kind of loop can become infinite.
Yes, the C++ version leaks due to new Command(...)
with no delete
. Of course it could have easily been coded differently to avoid that:
...
while (true) {
string commandSpecification = getUserCommandSpecification();
Command cmd(commandSpecification);
cmd.execute();
}
...
...so I'm not sure the example is as instructive as they think.
The C++ code is creating an endless number of Command
objects which are never deleted. In C++ there's no garbage collection. One must call delete
on all instances that were created by new
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With