CS253

This file defines the header for each page. An optional "icon" image (I use the textbook):

A link to enable editing of this page: Edit TopBar Replace this with info about this class:

CS253: Problem Solving with C++

Spring 2012

New Lab

Links to the various pages for this class:

Wish I could do this: * Schedule

Redefining new & delete

Description

In this lab, we’ll show how you can redefine the new/delete operators to achieve a variety of useful or bizarre results.

The files for this lab are available in ~cs253/pub/Labs/NewLab.

Please let me know if you have any question in any level.

Redefining global new/delete

Consider glob.cc. It redefines the global new and delete operators to add trace output. This could be useful in figuring out just when new and delete are being invoked.

Note the function signatures—at this level, new takes a size_t and returns a void *, whereas delete takes a void * and returns void. Since these functions deal with raw memory, they work with void *.

Please explain briefly why new returns void *.

Redefining class-specific new/delete

Consider class.cc. It redefines the class-specific new and delete operators to add trace output. This will not affect new and delete operations on other types, such as int or double.

Forbid new/delete for a specific class.

Try to compile forbid.cc. Does it compile? Why not?

Same thing, but with a Mixin

forbid-mixin.cc does the same thing as forbid.cc, but does it better.

For another popular example of a mixin, see the Boost class noncopyable

Error checking

Compile and execute errchk.cc. Observe the error message, and decide what caused it. How would you improve it to detect multiple deletions of the same memory? (You don’t need to write the code, just explain it.)

Scrubbing the memory

If you’re concerned about the contents of deleted memory getting reused, then you might consider the technique used in scrub.cc. What criteria would you use to decide on a value for memory? I think that it should be:

For example, a repeated string of “Jack” or “WTF!” would fit all of the above requirements. Notably, an odd value makes for a poor pointer, and would often cause a segmentation violation upon use.

Memory pooling

Run normal.cc.

Now, run pool.cc.

Templated version

Of course, it’s a pain to have to redefine new and delete for every class. After we study templates, you will be able to create a templated mixin to do the same for all classes.

Problems with this approach

Exercises

For extra fame & glory

Modified: 2012-03-17T09:41

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building