malloc. McGraw-Hill The Complete Reference Fourth Edition
Reklaam
Reklaam
C h a p t e r 2 9 : T h e D y n a m i c A l l o c a t i o n F u n c t i o n s
759
Using an invalid pointer in the call most likely will destroy the memory management mechanism and cause a system crash.
Related functions are calloc( ), malloc( ), and realloc( ).
malloc
#include <cstdlib> void *malloc(size_t size);
The malloc( ) function returns a pointer to the first byte of a region of memory of size size that has been allocated from the heap. If there is insufficient memory in the heap to satisfy the request, malloc( ) returns a null pointer. It is always important to verify that the return value is not null before attempting to use it. Attempting to use a null pointer will usually result in a system crash.
Related functions are free( ), realloc( ), and calloc( ).
realloc
#include <cstdlib> void *realloc(void * ptr, size_t size);
The realloc( ) function changes the size of the previously allocated memory pointed to by ptr to that specified by size. The value of size may be greater or less than the original.
A pointer to the memory block is returned because it may be necessary for realloc( ) to move the block in order to increase its size. If this occurs, the contents of the old block are copied into the new block—no information is lost.
If ptr is null, realloc( ) simply allocates size bytes of memory and returns a pointer to it. If size is zero, the memory pointed to by ptr is freed.
If there is not enough free memory in the heap to allocate size bytes, a null pointer is returned, and the original block is left unchanged.
Related functions are free( ), malloc( ), and calloc( ).
This page intentionally left blank
Chapter 30
Utility Functions
Copyright © 2003 by The McGraw-Hill Companies. Click here for terms of use.
761
Laadi alla
Reklaam