Friday, July 29, 2016

C Basics - Memory Management in C

C provides three distinct ways to allocate memory for objects:

Static memory allocation: space for the object is provided in the binary at compile-time; these objects have an lifetime as long as the binary which contains them is loaded into memory.

Automatic memory allocation: temporary objects can be stored on the stack, and this space is automatically freed and reusable after the block in which they are declared is exited.

Dynamic memory allocation: blocks of memory of arbitrary size can be requested at run-time using library functions such as malloc from a region of memory called the heap; these blocks persist until subsequently freed for reuse by calling the library function realloc or free.

Unless otherwise specified, static objects contain zero or null pointer values upon program startup. Automatically and dynamically allocated objects are initialized only if an initial value is explicitly specified; otherwise they initially have indeterminate values. If the program attempts to access an uninitialized value, the results are undefined.

The C programming language provides several functions for memory allocation and management. These functions can be found in the <stdlib.h> header file.

Allocating Memory Dynamically:
void *calloc(int num, int size);
This function allocates an array of num elements each of which size in bytes will be size.

void *malloc(int num);
This function allocates an array of num bytes and leave them initialized.

Resizing Memory:
void *realloc(void *address, int newsize);
This function re-allocates memory extending it upto newsize.

Releasing Memory:
void free(void *address);
This function releases a block of memory block specified by address.

Related topics:
Incomplete Type in C   |   Lifetime, Scope, Visibility and Linkage in C   |   Namespace in C   |   Complex and Abstract Declarations in C   |   Storage of Data Types in C   |   Standard Library in C

List of topics: C Programming

No comments:

Post a Comment