Text Box:  

CIS3355: Business Data Structures in C/C++

1.                           Fall 2003                                        

2. Dynamic Memory Allocation

 

 

 

 

11.10 Why do we need to allocate memory dynamically?

 

Introduction:

 

            All of the abstract data types we have seen so far have been bridled by a major constraint: we need a fixed number of contiguous blocks of RAM. There has been a request of RAM on a static basis.  In other words, once we request a specified amount of storage, that space is reserved even before we actually save any data to it, and it can not be used by any other part of the program.  What we need to be able to do now is to request additional RAM on a dynamic basis, or on-the-run, as we require it.

 

            Allocating memory dynamically generally requires the data structures and techniques we have been discussing.  Without the use of structured data objects and pointers, we could not be able to allocate memory dynamically.  The idea of linked lists, and how to use linked lists to reduce search times contributes to the efficiency of dynamic memory allocation.  Used in conjunction, these structures and approaches allow us flexibility far beyond that possible with many of the older 3rd generation languages, such as COBOL or FORTRAN.

 

What are the advantages of allocating memory dynamically?

 

1. We do not have to have contiguous blocks of RAM

2. We do not need to specify how much memory we require in advance

3. We use only the amount of RAM we need

4. We free-up RAM when we don’t need it (and reuse later if we do)

5. We can get more RAM than if we attempt to request large blocks of RAM

 

        How do we request RAM dynamically?

                To allocate RAM, we would issue the command:

         newdata = (struct mydata *) malloc(sizeof(struct mydata));

 

                How do we know if we don’t have the contigous memory we need for our data type?

            When the function malloc returns a NULL address.