Dynamic Allocation of Memory - PowerPoint PPT Presentation

1 / 13
About This Presentation
Title:

Dynamic Allocation of Memory

Description:

Allocation of Memory: C Style. Use the operator new. Allocate memory for a single object ... an address that was previously returned by new. delete ptr; ... – PowerPoint PPT presentation

Number of Views:41
Avg rating:3.0/5.0
Slides: 14
Provided by: robbko
Learn more at: http://people.hsc.edu
Category:

less

Transcript and Presenter's Notes

Title: Dynamic Allocation of Memory


1
Dynamic Allocation of Memory
  • Lecture 4
  • Secs 2.4, 3.2, 3.4
  • Thu, Jan 24, 2008

2
Vectr Objects
  • Non-empty Vectr
  • Empty Vectr

3
The Vectr Class Interface
  • The Vectr class interface
  • vectr.h
  • Related files
  • vectr.cpp
  • VectrTest.cpp

4
Allocation 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)
5
Allocation 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))
6
Deallocation 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)
7
Dynamic 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)
8
Example DynamicCArray.cpp
9
Allocation 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
10
Deallocation 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
11
Example DynamicCArray.cpp
12
The Vectr Class Implementation
  • The Vectr class implementation
  • vectr.cpp

13
Example VectrTest.cpp
Write a Comment
User Comments (0)
About PowerShow.com