14
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation Java dynamic allocation example The malloc() function 'C' dynamic allocation example

Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation

Embed Size (px)

Citation preview

Page 1: Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation

Dynamic Memory Allocation

Conventional array and other data declarations

An incorrect attempt to size memory dynamically

Requirement for dynamic allocation

Java dynamic allocation example

The malloc() function

'C' dynamic allocation example

Page 2: Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation

Conventional data declarations

These all require that the amount of memory needed in bytes is known at compile time.

There are 3 types:

1. Global memory variables

2. Automatic memory variables

3. Static memory variables

Page 3: Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation

Global memory variables

These are memory variables declared outside of the functions and accessible to all functions without having to be declared more than once or passed as parameters.

Justified in few cases, but in others this breaks modularisation of data and complicates and hides communication between functions. Misuse of globals causes difficult to find bugs and more buggy programs.

typedef struct student {int startyear;char name[30];

} STUDENT;STUDENT sdn[50]; /* global array of student records */

int main(void){ ...

Page 4: Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation

Automatic memory variables

Automatic memory variables use memory which is automatically allocated at runtime when a function is entered, and this memory is automatically recovered (garbage collected) when the function exits.

float cube(float value){ /* parameters are automatic*/float result; /* automatic memory variable */...

Page 5: Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation

Static memory variablesStatic memory variables are declared using the static keyword.

As with automatic variables, static data are also useful for modularising data within functions, enabling clean and visible interfaces between functions and easier debugging. Unlike automatic variables, they exist for as long as the entire program runs. They are useful for data made accessible through pointers elsewhere, and for values which needs to be preserved between calls to the same function.

void printprime(int prime){/* prints primes in rows of 8 columns */static int col=0; /* only initialised once */ col++; /* add 1 each time function is called */...

Page 6: Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation

Incorrect attempt at dynamic memory sizing

The compiler must know how much memory to allocate for the above 3 memory types. This means

that arrays declared using approaches such as:

float fa[N];

require that N is a constant the value of which is known at compile time.

Page 7: Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation

Incorrect attempt at dynamic memory sizing

This approach will not work

int size;float *fp;printf("enter number of elements\n");scanf("%d",&size);fp=makearray(size);...float *makearray(int size){ static float fa[size]; /* wrong !! */ return fa;}

Page 8: Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation

Requirement for dynamic memory allocation

A program is likely to have to optimise use of memory. Flexibility requires that the source code should not need to be changed to match the amount of data to the memory available and recompilation with different sizes for data structures might not be practical.

You might want to use the same program on a mainframe capable of handling millions of records or on an embedded system where memory only exists for a few thousand.

In some programs the application needs allocation and freeing of memory to be under program control at points in the running program not matching the rules for the other memory types described so far.

Page 9: Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation

Java Example

Other programming languages with object oriented features typically use the new keyword to allocate space for, and return references to non-trivial newly created objects.

BufferedReader in=Text.open(System.in); // allocate input stream, requires Text class

Text.prompt("how many frequencies ?"); // prompt user

int numf=Text.readInt(in); // read number of frequencies required

int frequencies[] = new int[numf]; // frequencies is now an array of integers

Page 10: Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation

'C' Example 1

The 'C' programming language uses the malloc() function for this purpose.

int *frequencies, numf;/* pointer to start of and size of array */

printf("how many frequencies ?\n"); /* prompt user */scanf("%d",&numf);

/* read number of frequencies required */frequencies = (int*) malloc(sizeof(int)*numf); /* frequencies now points to an array of integers */

Page 11: Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation

The malloc() function

void *malloc(size_t); /* function prototype */

malloc() requires one parameter of type size_t, this is an integral type such as might be returned by sizeof().

This parameter is the amount of memory which malloc() is required to allocate in bytes.

malloc() returns a void pointer, which is a valid address to the contiguous block of memory allocated, but of no specific type, because malloc() doesn't know what data type the memory allocated will be used for.

Page 12: Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation

Example call of malloc

frequencies = (int*) malloc(sizeof(int)*numf);

The void pointer returned is cast to become a pointer to int using the (int*) cast operator, so that the memory allocated will be used to store integers. The size in bytes of an integer variable is returned by sizeof(int). This is multiplied by numf, the number of integers required, so the number of bytes needed for the integer array are allocated. The pointer frequencies may now be used to access an array of numf integers. The first integer is addressed as frequencies and accessed as

frequencies[0] and the last integer in the array may be accessed as frequencies[numf-1]

Page 13: Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation

Using the free() function

Most production programs written in 'C' use dynamic memory for most program data because of the flexibility this allows. But for a server program running 24x7x365, memory allocated for data to meet each client request has to be freed after use or the memory leakage will kill the program. When the data are no longer needed, the free function is called to free the allocation:

free(pointer_variable); /* garbage collection R US */

Page 14: Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation

More 'C' Examples

http://copsewood.net/tic/dsalg/dynamic/mallstr.html

http://copsewood.net/tic/dsalg/dynamic/mallocex.html