In the first lecture we talked about C as the "manual transmission" of programming languages. One place where the explicit nature of the language is in dynamic memory management.
So far we have seen two kinds of storage:
This kind storage is implicit in object oriented languages like Java and C++. For example, in Java if you have a class Planet you create a new object of that class with
Planet tera = new Planet();This automatically allocates storage to hold all the fields of the new Planet object and associates a set of methods with that object. The storage for the object is implicitly reclaimed when there are no longer any references to the object. Automatic storage management is integrated deeply into the language.
In C, we allocate storage manually by calling malloc. It is a general purpose storage allocator. We call it for any object. It doesn't even know what kind of object we are talking about. It just allocates a contiguous chunk of bytes. It's signature is
void *malloc(unsigned nbytes);When we use it we have to tell it what of object we are talking about. Malloc returns a pointer to space for an object of size nbytes, or NULL if the request cannot be satisfied.
For example
char *p = (char *) malloc(17);causes p to point to a newly allocated chunk of empty space that is at least 17 bytes in size.
If you allocated such space, you could discard it manually with
free(p);
Be sure that it is no longer needed before you free it, otherwise very confusing and usually bad things are likely to happen.
Both of these functions are defined in <stdlib.h>, along with from fancier tools. They are standard in C implementation, but much less deeply integrated into the language than, say new in Java.