C对Java:无限循环创建对象只会崩溃C

这是我的一本书中的一个问题(没有回答),我一直在想几天。答案只是C代码最终会崩溃,因为它在每次迭代之后创建一个垃圾内存单元?

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代码

...
while (true) {
   String commandSpecification = getUserCommandSpecification();
   Command cmd = new Command(commandSpecification);
   cmd.execute();
}
...

C代码

...
while (true) {
   string commandSpecification = getUserCommandSpecification();
   Command* cmd = new Command(commandSpecification);
   cmd -> execute();
}
...
是的,C版本泄漏是由于新的Command(…)而没有删除。当然,它可以很容易地被编码不同以避免:

...
while (true) {
   string commandSpecification = getUserCommandSpecification();
   Command cmd(commandSpecification);
   cmd.execute();
}
...

…所以我不知道这个例子是否像他们想的那样有启发性。

http://stackoverflow.com/questions/13338340/c-vs-java-endless-loop-creating-objects-only-crashes-c

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:C对Java:无限循环创建对象只会崩溃C