Beginning Section 3.5 of Shiflet text.

Dynamic Memory Allocation

We don't always know how much memory is needed beforehand. Create code so we can allocate memory for data as needed.

The routines Push() and AddQueue() should not fail.

Dynamically created memory does not have a name as variables do so we need a reference for it. Use a pointer (also called an address, a link, a reference).

Typically we use pointers to structures (Fig 4.1).

Linked Lists

A set of structures linked together where one structure points at the next. Use ground symbol for NULL pointer. Draw a picture.

Compare with arrays, which use contiguous storage. It is possible to index into an array.

Types

Pointer variables are bound to a particular type of value to which it points.

struct NodeType {
    . . .
};

char *pch1, *pch2;
NodeType *pNode1, *pNode2;

Can set a pointer to another pointer of the same type, but not of different types.

NULL pointer

The constant NULL is actually

#define	NULL	0

It can be used for a pointer of any type--it is generic. It is commonly used to indicate the pointer is not pointing to any address.

Note: A pointer variable is not by default initialized to NULL (or any other value). Following will produce an error. Why?

char *pch;
char ch;

*pch = 'a';  // not ok
pch = &ch;
*pch = &ch;  // now ok

Dynamic Memory Creation

In C++, the new operator is used to create memory. It takes one argument--the type of space to create.

In C, the library function malloc() is used to create memory. It takes one argument--the amount of memory to allocate.

Example1: to create a structure (or any type);

NodeType *pNode;

pNode = new NodeType;

if (pNode == NULL)

C version:

NodeType *pNode;

pNode = (NodeType *)malloc(sizeof(NodeType));

if ((pNode = (NodeType *)malloc(sizeof(NodeType))) == NULL)

where sizeof() returns the size of what is given in bytes.

Example 2: to copy a string (be sure and use strlen() + 1)

char sbBuf[100], *pch;
 
cin.getline(sbBuf, 100);
pch = new char[strlen(sbBuf)+1];
if (pch == NULL) {
    cout << "Memory exhausted.\n";
    exit(1);
}
strcpy(pch, sbBuf);
cout << pch << "\n";

C version:

char sbBuf[100], *pch;
 
scanf("%s\n", sbBuf);
if ((pch = malloc(strlen(sbBuf)+1)) == NULL) {
    printf("Memory exhausted.");
    exit(1);
}
strcpy(pch, sbBuf);
printf("%s\n", pch);

Delete

To return dynamically allocated memory use the operator delete and pass it the value of a pointer. In C the function free() is used.

delete [] pch;  // must explicitly indicate arrays
delete pNode;
free(pNode);