|
|
Dynamic Memory Allocation |
|
void *malloc (size_t size) |
Allocates size bytes and returns a pointer to it
|
void *calloc (size_t n_elem, size_t size) |
Allocates memory for an array of n_elem elements of
size bytes each and returns a pointer to the allocated
memory. The memory is initialized to zero.
|
void free (void *ptr) |
Frees previously allocated memory |
#include <stdio.h>
#include <stdlib.h>
#define NUM 10
int main ( void ) {
int *ptr,
*ptr_inc;
/*
* allocate NUM integers
*/
if ( NULL == ( ptr = calloc ( NUM, sizeof ( int ) ) ) ) {
printf ( "Unable to allocate memory. Exiting...\n" );
return ( 1 );
}
/* set the values */
for ( ptr_inc = ptr; ptr_inc < ( ptr + NUM ); ptr_inc++ )
*ptr_inc = ptr_inc - ptr;
/* print the values */
for ( ptr_inc = ptr; ptr_inc < ( ptr + NUM ); ptr_inc++ )
printf ( "%d\n", *ptr_inc );
/* free the memory */
free ( ptr );
return ( 0 );
}
Output:
0 1 2 3 4 5 6 7 8 9