Jump to content

C++ Programming/Code/Standard C Library/Memory

From Wikibooks, open books for an open world

Standard C Memory Management

[edit | edit source]

This section covers memory management elements from the Standard C Library.

Note:
It is recommended to use smart pointers' like unique_ptr<type> for code since C++ 11, and the new and delete operators for older code. They provide additional control over the creation of objects.

calloc

[edit | edit source]
Syntax
#include <cstdlib>
void *calloc( size_t num, size_t size);

The function calloc() allocates a block of memory that can store an array of num cells, each with a size size. Every cell of the array is set to value zero.

If the operation fails, calloc() returns "NULL".

EXAMPLE:

     ptr = (float*)calloc(25, sizeof(float));
     /* It would create an array of 25 cells, each one with a size of 4 bytes
        “(sizeof(float))”, all the cells initialized with value 0 */
Related topics
free - malloc - realloc
Syntax
#include <cstdlib>
void free( void *p);

The function free() releases a previously allocated block from a call to calloc, malloc, or realloc.

Related topics
calloc - malloc - realloc

malloc

[edit | edit source]
Syntax
#include <cstdlib>
void *malloc( size_t s );

The function malloc() allocates a block of memory of size s. The memory remains uninitialized.

If the operation fails, malloc() returns NULL.

Related topics
calloc - free - realloc

realloc

[edit | edit source]
Syntax
#include <cstdlib>
void *realloc( void *p, size_t s);

The function realloc() resizes a block created by malloc() or calloc(), and returns a pointer to the new memory region.

If the resize operation fails, realloc() returns NULL and leaves the old memory region intact.

Note:
realloc() does not have a corresponding operator in C++ - however, this is not required since the standard template library already provides the necessary memory management for most usages.

Related topics
calloc - free - malloc