malloc (memory allocation) is used to dynamically allocate memory
at run time. Possible uses for this function are:
The simplest way to reserve memory is to code something like:
- Read records of an unknown length.
- Read an unknown number of database records.
- Link lists.
strcpy (string, "Some text");
The example above has two problems:
malloc allows us to allocate exactly the correct amount of memory and
with the use of free only for the time it is required.
- If the data is less than
1000 bytes we are wasting memory.
- If the data is greater than 1000 bytes the program is going to crash.
- The 1000 bytes are reserved throught out the life of the program.
If this was a long running program that rarely used the memory, it would
again be wasteful.
Prototype: void *malloc(size_t size);
Syntax: char * String;
String = (char *) malloc(1000);
Looking at the example syntax above, 1000 bytes are reserved and the pointer
String points to the first byte. The 1000 bytes are NOT initialized
by malloc. If the memory is NOT available, a
NULL pointer is returned.
Please note, the cast cast is required to
return a pointer of the correct type.
char data type.
new is the C++ equivalent to malloc.
delete is the C++ equivalent to