Dynamic Memory Allocation

malloc

void * malloc (size_t s) 
//size_t defined in stdlib.h
int * arr = malloc(5 * sizeof(int));
//allocate memory for an int array of size 5

calloc

calloc() works like malloc, but initializes the memory to zero if possible. The prototype is:

void *calloc(size_t num, size_t size);
// equivalent to malloc()
void *malloc(size_t num * size)

Num is the number of elements, and size the byte size of each element.

realloc

void* realloc (void * p, size_t s);

Extend or shrink the block pointed by p to s bytes

Safe instructions to use realloc
int *tmp;
if ((tmp = realloc(ip, sizeof(int) * (INITIAL_ARRAY_SIZE + 5))) == NULL) {
    fprintf(stderr, "ERROR: realloc failed");
}
ip = tmp;

If realloc fails to extend memory pointed by ptr, ptr will point to NULL, and its previous allocated memory will never be accessed (memory leak).

bzero

bzero(3) fills the first n bytes of the pointer to zero. Prototype:

void bzero(void *s, size_t n);

memset

To set the value to some other value (or just as a general alternative to bzero).

void *memset(void *s, int c, size_t n);

Specify c as the value to fill for n bytes of pointer s.

free

void free(void * ptr)

Free the heap block pointed by p

int *p = malloc(8);
// allocated 8 bytes to p
free(p);
free(p); //program crashes [runtime error]

After freeing a pointer, should point it to NULL.

Published on October 16, 2015