Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ vs Java: endless loop creating objects only crashes C++

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();
}
...
like image 884
caleb.breckon Avatar asked Nov 12 '12 04:11

caleb.breckon


People also ask

Can an infinite loop crash your computer?

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.

Why does an infinite loop crash?

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.


2 Answers

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.

like image 146
Ben Jackson Avatar answered Oct 04 '22 17:10

Ben Jackson


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.

like image 22
xxbbcc Avatar answered Oct 04 '22 18:10

xxbbcc