This preview shows page 1. Sign up to view the full content.
Unformatted text preview: ptr var = new DataType[size];
Object Programming Object Programming The value of ptr may or may not be set to 0 by
this action. It may still point to the old memory
which has now been given up.
Such a pointer is called a dangling pointer.
Set such a pointer to 0 to ensure that we do not
continue to use the deleted space.
For arrays of memory allocated by new we use
delete DBase; Get used to deleting dynamically allocated
memory once their usage is complete.
Avoid memory leaks.
ptr } automatic variable ptr = new int;
. . . ptr is destroyed 100 ints leaked
unless we delete ptr
ptr Object Programming How does delete know the amount of memory
associated with a pointer?
Each new operation doesn't just allocate the
Each new operation
memory requested. It tacks on a couple of bytes
to let delete know how much there is.
This is the overhead of new.
new Object Programming Be also aware that there are rules about what
sort of address certain types must start on.
Usually it has to at least be even.
char *c1, *c2;
c1 = new char;
c2 = new char;
yields addresses 4 bytes apart. Object Programming This new power we've unleashed is more than
just a way of dynamically allocating space.
Its strengths lie in the ability to define new data
structures beyond the traditional scalars and
Let's look at another example to illustrate this new
window of opportunity.
Object Programming Overhead is implementation dependent. Programming
Object A pizza restaurant allocates tables on a
first-come, first-served basis.
give their names and party size
take a seat and wait
The receptionist keeps a list of customers in the
order they arrive.
W hen a table becomes available, the name on
the top of the list is served.
Object Programming To computerise this process we create a
struct W e then declare one single pointer to the
customer at the top of the list
CustPtr Head; struct Cust
}; Initially, the list is empty. So we set
Head = 0; typedef Cust* CustPtr;
next is a pointer to the next customer on the list. So, what sort of things do we want to do with
such a list?
such Object Programming When a customer arrives
add the customer to the bottom of the list
When a table becomes available
get the first name off the list
and remove it from the list Object Programming 0 Algorithms:
set Head to 0
create a new customer
link it to the tail of the list So we have three functions:
Head Object Programming Cust1
if there is a customer on the list
get the customer's name and party size
make the head point at the next customer
delete the memory used by the old head
return the name and party size
Object Programming Cust1
Head tmp tmp Initialise
Add Add Object Programming...
View Full Document
- Spring '14