C (programming language)

Revision as of 20:21, 9 February 2021 by David (talk | contribs)
\( \newcommand{\P}[]{\unicode{xB6}} \newcommand{\AA}[]{\unicode{x212B}} \newcommand{\empty}[]{\emptyset} \newcommand{\O}[]{\emptyset} \newcommand{\Alpha}[]{Α} \newcommand{\Beta}[]{Β} \newcommand{\Epsilon}[]{Ε} \newcommand{\Iota}[]{Ι} \newcommand{\Kappa}[]{Κ} \newcommand{\Rho}[]{Ρ} \newcommand{\Tau}[]{Τ} \newcommand{\Zeta}[]{Ζ} \newcommand{\Mu}[]{\unicode{x039C}} \newcommand{\Chi}[]{Χ} \newcommand{\Eta}[]{\unicode{x0397}} \newcommand{\Nu}[]{\unicode{x039D}} \newcommand{\Omicron}[]{\unicode{x039F}} \DeclareMathOperator{\sgn}{sgn} \def\oiint{\mathop{\vcenter{\mathchoice{\huge\unicode{x222F}\,}{\unicode{x222F}}{\unicode{x222F}}{\unicode{x222F}}}\,}\nolimits} \def\oiiint{\mathop{\vcenter{\mathchoice{\huge\unicode{x2230}\,}{\unicode{x2230}}{\unicode{x2230}}{\unicode{x2230}}}\,}\nolimits} \)

C is the low-level programming language taught in UMD's CMSC216 class.

Usage

Memory Allocation

#include <stdlib.h>
There are 3 ways to allocate memory in C

  • malloc(bytes) Allocated memory is uninitialized.
  • calloc(number, bytes) Allocated memory is initialized to 0. Allocates (number * bytes) bytes of memory.
  • alloca(bytes) Discouraged

Memory allocated by malloc and calloc are on the heap and should be deallocated by free when no longer used to avoid memory leaks.
Memory allocated by alloca is allocated on the stack and will automatically be freed. Do not call free on this memory. Do not allocate more than a few bytes using alloca or you will risk a stack overflow leading to undefined behavior.
For automatic garbage collection, use C++ which has smart pointers.

_malloca

On Windows you also have:

  • _malloca
  • _calloca

These are not portable so I wouldn't use them. They are a safer version of alloca which allocates to the heap if there isn't enough stack space. However, you need to free them using _freea which eliminates the main benefit of alloca.
As far as I can tell, the only benefit is to prevent heap fragmentation.