Next: Exercises Up: Common Pointer Pitfalls Previous: Not assigning a pointer to memory address

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;


~*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:
Wed Sep 14 10:06:31 BST 1994