malloc function
malloc (memory allocation) is used to dynamically allocate memory
at run time. Possible uses for this function are:
- Read records of an unknown length.
- Read an unknown number of database records.
- Link lists.
The simplest way to reserve memory is to code something like:
main()
{
char string[1000];
strcpy (string, "Some text");
}
|
The example above has two problems:
- 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.
malloc allows us to allocate exactly the correct amount of memory and
with the use of free only for the time it is required.
Library: stdlib.h
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.
Examples:
example
program.
See Also:
char data type.
free function.
sizeof operator.
C++
new is the C++ equivalent to malloc.
delete is the C++ equivalent to
free.
Martin Leslie