It is an error to call the delete operator on a pointer a second time. Consider what happens if there is memory allocated on the free store for a class, a destructor, and initializing constructors have been defined, but no copy constructor was defined. Now suppose a function is called that has call-by-value parameters. Why does the program either die in the middle or give a segmentation fault?

What will be an ideal response?


The call-by-value parameters cause the default (compiler generated) copy constructor to be called. The default copy constructor copies the pointer members of the class. This makes the value parameters class object’s pointers point to the argument’s data. When the function terminates, the destructor is called on the parameter. The destructor calls delete on the pointers in parameter. Unfortunately, this data is the same data that the argument’s pointers point to, so the argument’s pointers are now dangling. When the argument goes out of scope, the destructor is called. This calls delete on pointer variables in the argument object. The result it that these pointer have been deleted twice, once at function termination and once when the argument goes out of scope. The result is a segmentation fault, which either causes the program to crash or causes a segmentation fault. Segmentation fault are usually reported after the program terminates. The moral is that if you have any of destructor, copy constructor or operator = you likely need all three. (This actually occurred to this writer while writing another textbook.)

Computer Science & Information Technology

You might also like to view...

Design units are used to specify the __________ of a Font.

a) Size b) Name c) FontFamily d) Style

Computer Science & Information Technology

The company security policy led to the installation of a VPN concentrator and a RADIUS server. With only these devices installed, which of the following goals are not possible to achieve?

A. All data must be encrypted. B. All connections must be authenticated. C. Only certain external networks can be the source of a connection. D. All connections must be authorized.

Computer Science & Information Technology

An organization should not permit end users to install anything on their computer

Indicate whether the statement is true or false.

Computer Science & Information Technology

Which of the following is NOT a strategy that supports green computing?

A. using energy efficient hardware B. regulating manufacturing processes C. recycling D. creating web apps instead of desktop apps

Computer Science & Information Technology