Title: Dynamic Allocation of Memory
1Dynamic Allocation of Memory
- Lecture 4
- Secs 2.4, 3.2, 3.4
- Thu, Jan 24, 2008
2Vectr Objects
- Non-empty Vectr
- Empty Vectr
3The Vectr Class Interface
- The Vectr class interface
- vectr.h
- Related files
- vectr.cpp
- VectrTest.cpp
4Allocation of Memory C Style
- The library function malloc() allocates a
specified number of bytes of memory and returns a
pointer to it. - Include the header file ltcstdlibgt.
- Prototype
void malloc(int number-of-bytes)
5Allocation of Memory C Style
- malloc() returns a pointer to the first byte of
the allocated memory block. - The returned pointer is a pointer to void.
- The returned pointer must be cast to the proper
type.
int pi (int)malloc(sizeof(int)) Point2D pdt
(Point2D)malloc(sizeof(Point2D))
6Deallocation of Memory C Style
- The library function free() deallocates memory.
- Include the header file ltcstdlibgt.
- Prototype
- The pointer must contain an address that was
previously returned by malloc().
void free(void ptr)
7Dynamic Memory for Arrays C Style
- Allocate memory for an array
- Deallocate memory for an array
- The computer remembers the size of the array.
Type ptr (Type)malloc(sizesizeof(Type))
free(ptr)
8Example DynamicCArray.cpp
9Allocation of Memory C Style
- Use the operator new.
- Allocate memory for a single object
- Allocate memory for an array of objects
Type ptr new Type
Type ptr new Typesize
10Deallocation of Memory C Style
- Use the operator delete.
- Deallocate memory for a single object
- Deallocate memory for an array of objects
- The pointer must contain an address that was
previously returned by new.
delete ptr
delete ptr
11Example DynamicCArray.cpp
12The Vectr Class Implementation
- The Vectr class implementation
- vectr.cpp
13Example VectrTest.cpp