Notes

C - Memory allocation

author: Paul Kim

categories: c

tags: c

Memory allocation in C

Objectives

Be able to recognize the difference between static and dynamic memory allocation

Be able to use malloc() and free() to manage dynamic memory in your programs

Be able to analyze programs for memory management related bugs

Allocation

For all data, memory must be allocated (memory space must be reserved).

We can allocate memory either during compile-time (static) or run-time (dynamic)

How much memory to allocate?

Sometimes its obvious:

char  c;        // one byte
int   arr[10];  // 10 * sizeof(int)

Sometimes its not so obvious:

char  *c;       // is this going to point to one character or a string?
int   *arr;     // how big will this array be?

malloc()

#include <stdlib.h>   // need to include this directive to use malloc()

int *arr = malloc(num_items * sizeof(int));

Using malloc()

// statically allocates space for 2 pointers
int *i;
int *arr;

// dynamically allocates space for data
i = malloc(sizeof(int));
arr = malloc(num_items * sizeof(int));

*i = 3;
arr[3] = 5;

Note: allocated memory is NOT initialized!

calloc() zeros allocated memory (otherwise, same as malloc())

// always check the return value of system calls like malloc() for errors
int *a = malloc(num_items * sizeof(int));
if (a == NULL) {
  fprintf(stderr, "out of memory.\n");
  exit(1); // terminate now and indicate error
}

Deallocation

malloc() allocates memory explicitly. we must also deallocate it explicity using free()

there is no automatic deallocation (garbage collection) as in Python and Java

int *a = malloc(num_items * sizeof(int));

free(a);

// must not use a freed pointer unless reassigned or reallocated
a = malloc(2 * num_items * sizeof(int));

Space allocated by malloc() is freed when the program terminates.


ChromeEdgeFirefoxOpera

© 2021 paulkode.com. All rights reserved.