Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation."— Presentation transcript:

1 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

2 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

3 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){...

4 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 */...

5 Static memory variables Static 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 */...

6 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.

7 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; }

8 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.

9 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

10 '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 */

11 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.

12 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]

13 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 */

14 More 'C' Examples http://copsewood.net/tic/dsalg/dynamic/mallstr.html http://copsewood.net/tic/dsalg/dynamic/mallocex.html


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

Similar presentations


Ads by Google