Anda di halaman 1dari 24

Memory Management

Junaed Sattar September 17, 2008 Lecture 3

Today

memory management

C++ memory management issues dynamic memory (de)allocation pointers

Memory structure (simplified)


High address Command line arguments Environment variables

Stack (Function/method arguments, locals, return addresses)

Free store (Heap) Dynamically allocated memory

Code (Read-only) Uninitialized/Initialized data (No eXecute) Low address

Memory basics

C++ (as well as C) provides mechanisms for dynamic memory allocation


ask for memory as we need it let it go when we don't possible to write memory-efficient code (small memory footprint)

Memory basics

The catch(es):

Somewhat complex mechanism for doing so Manual (i.e. programmer-initiated) memory management Coding mistakes leads to ugly, hard-tofind, hard-to-replicate bugs No automatic garbage collection

One scenario

Loading an image from disk for display


locate the file and format (jpg/tiff/bmp/png...) allocate enough memory to hold the image copy the image from disk to memory process deallocate the memory previously allocated

The allocate-use-deallocate cycle must be maintained

Graphically...
Main memory

find image

Secondary memory

Graphically...
Main memory find image calculate size

645KBytes

Secondary memory

Graphically...
Main memory find image calculate size allocate memory

645KBytes

dynamically allocate

Secondary memory

Graphically...
Main memory find image calculate size allocate memory

645KBytes

Secondary memory

Simple workflow, but...

Task for the programmer to do all that

unlike Java, where the compiler/interpreter takes care of it Programmers must clean up themselves what if not enough free memory?

No automatic garbage collection

Memory allocation requests might fail

Pointers

holds the address of a data object or a function/method handler to dynamically allocated memory pass arguments as reference

we've seen this last class

Pointers

declaration

int *i; char *c; and so on. i.e. the same pointer cannot refer to ints and chars

refers to objects of one data type only

Pointers

simple usage:

int number = 10; int *i = &number; i contains the address of number *i contains the value stored in number

*i is a pointer to an int

i.e. *ihas the value stored at the address pointed to by i

Pointers

stray pointer:

int *i; undetermined, random address Stray or uninitialized pointer.

i points to what?

using a pointer without initialization has undefined results

in other words, big bad bug.

Bad Pointer
int*i; intnum=10; ... *i=100;//Whereisthisgoingto???

This program:

will compile,will run, and maybe will not even crash depending on what i points to, it might bring down your program entirely always initialize with either a valid address or NULL

Allocation

usage:

int *i = new int; dynamically allocated space for one int using the C++ new operator find storage in free store (or heap) returns a pointer to the object created

*i is a pointer to an int, but also we have:


new provides dynamic storage allocation


More about new

new can fail

if it does, then either returns NULL or throws an exception (std::bad_alloc) int *i = new int(10); note the bracket type int *i = new int[10];

can be used to initialize the memory:


can be used to allocate arrays:

new example
char*pCharArray; try{ pCharArray=newchar[256]; //sampleusage strcpy(pCharArray,"Arrayofcharacters"); } catch(std::bad_alloce) { std::cerr<<Allocationfailed.; }

Deallocation

an object created with new exists until operator delete is used to deallocate will not be implicitly called for an object created with a new

must explicitly deallocate otherwise will create memory holes

Deallocation

new and delete must come in pairs use correct matches


use delete() with new() (individual objects) use delete[]() with new[]() (arrays)

if not, the result is undefined deleting a NULL pointer has no effect. delete does not assign NULL to a pointer accessing a deleted pointer has undefined effects

delete example
char*pCharArray=0; try{ pCharArray=newchar[256]; } catch(std::bad_alloce) { std::cerr<<Allocationfailed.; } ... delete[]pCharArray; pCharArray=NULL;

memory holes?
voidSomeFunction(){ char*pCharArray=0; try{ pCharArray=newchar[256]; } catch(std::bad_alloce){ } ... } intmain(){ SomeFunction(); } std::cerr<<Allocationfailed.;

memory F.A.Q.

why new and not malloc?

support for objects and type-safe pointers causes prorgam to crash bad idea.

double delete?

mixing new/malloc?

Anda mungkin juga menyukai