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...

Match the following terms to their meanings:

I. Min II. Max III. Avg IV. Sum V. Count A. Totals the values in a field B. Averages the values in a field C. Displays the largest value in a field D. Displays the smallest value in a field E. Displays the number of records based on a field

Computer Science & Information Technology

What does an eyedropper do?

A) It captures the exact color from an object on your slide. B) It duplicates up to three colors on a slide. C) It captures a shape and duplicates it as many times as requested. D) It captures an image so it can be duplicated.

Computer Science & Information Technology