malloc(), free() and sizeof()

Chapter: malloc(), free() and sizeof()

The call malloc(n), where n is an unsigned int, returns a pointer to the beginning of a newly allocated block of n contiguous bytes. Since it returns a pointer to the newly allocated block, it is convenient, as we mentioned in the previous chapter, for the calling program to be using pointers.

The call free(p) where p is a pointer to some data causes that data to become unavailable. Conceptually, it is returned to the unallocated memory pool and is available for re-allocation by another call to malloc().

How do you know how many bytes to allocate? One way is to count how many bytes are specified in your struct. That's one byte for a char, two for an int. Or is it? Most computers nowadays provide four bytes for an int. To increase portability and for the sake of your own sanity, it's a good idea to let the compiler do the (architecture-specific) counting for you. In addition to malloc() and free() the standard library also provides the sizeof() function, to which you can submit your data structure and which will return its size in bytes. Typically, if you declare a

 struct myNode {
   data whatever...
 };
and a pointer to a struct myNode as
  struct myNode *myNodePtr;
you will allocate storage for such a node using a line like:
  myNodePtr = malloc(sizeof(struct myNode));

One last note: The three functions malloc() free() sizeof() reside in the standard library. They are not officially part of the C language. To use them, you should include the line

#include < stdlib.h >
(omitting the anti-HTML spaces of course) at the top of your file. If not, you must expect weird error messages like:
warning: incompatible implicit declaration of built-in function 'malloc'


rhyspj@gwu.edu