Tuesday, January 11, 2011

C Memory Related Functions

malloc

Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.
The content of the newly allocated block of memory is not initialized, remaining with indeterminate values.
Syntax: (size_t*) malloc(size);
Return type void. If some errors return NULL.

calloc

Allocates a block of memory for an array of number elements, each of them size bytes long, and initializes all its bits to zero.
The effective result is the allocation of an zero-initialized memory block of (number * size) bytes.
Syntax: (size_t*) calloc(size);
Return type void. If some errors return NULL.

realloc

The size of the memory block pointed to by the ptr parameter is changed to the size bytes, expanding or reducing the amount of memory available in the block.
The function may move the memory block to a new location, in which case the new location is returned. The content of the memory block is preserved up to the lesser of the new and old sizes, even if the block is moved. If the new size is larger, the value of the newly allocated portion is indeterminate.
In case that ptr is NULL, the function behaves exactly as malloc, assigning a new block of size bytes and returning a pointer to the beginning of it.
In case that the size is 0, the memory previously allocated in ptr is deallocated as if a call to free was made, and a NULL pointer is returned.

free

A block of memory previously allocated using a call to malloc, calloc or realloc is deallocated, making it available again for further allocations.
Notice that this function leaves the value of ptr unchanged, hence it still points to the same (now invalid) location, and not to the null pointer.

0 comments:

Visitors Count

Free Hit Counter