49


Illegal indirection

Suppose we have a function malloc() which tries to allocate memory dynamically (at run time) and returns a pointer to block of memory requested if successful or a NULL pointer otherwise.

char *malloc() - a standard library function (see later).

Let us have a pointer: char *p;

Consider:

*p = (char *) malloc(100);   /* request 100 bytes of memory */

*p = `y';

There is mistake above. What is it?

No * in

*p = (char *) malloc(100); !

Malloc returns a pointer. Also p does not point to any address.

The correct code should be:

p = (char *) malloc(100);

If code rectified one problem is if no memory is available and p is NULL.

Therefore we can't do:

*p = `y';.

A good C program would check for this:

p = (char*) malloc(100);

*p = 'y';


drago@scri.fsu.edu
Jan. 1997