Guardian C Library Calls Reference Manual
malloc
3-112 128833—Guardian TNS C Library Calls Reference Manual
Reference to Library Calls
malloc
The malloc function allocates memory starting on a word boundary.
nbytes
specifies the number of bytes to allocate.
Return Value
points to the allocated memory if the operation is successful; otherwise, malloc
returns the pointer value NULL.
Usage Guidelines
•
Note that malloc returns a pointer of type void, which is compatible with any pointer
type. However, if you explicitly specify the intended type using a cast expression,
your code will be more maintainable and readable. Both of the following examples
show the intended type using a cast expression.
•
If you have compiled your program for the large-memory model, the malloc
function will automatically enlarge the extended data segment when necessary.
•
Each call to the malloc function should have a corresponding call to the free
function to avoid blocks of allocated memory that are no longer in use.
Examples
1. This example allocates memory for a char array of 10 elements:
#include <stdlibh>
char *ptr;
/* ... */
ptr = (char *)malloc(10*sizeof(char));
2. This example allocates memory for an int array of 5 elements:
#include <stdlibh>
int *ptr;
/* ... */
ptr = (int *)malloc(5*sizeof(int));
#include <stdlibh>
void *malloc(size_t nbytes);