C (programming language): Difference between revisions

From David's Wiki
(Created page with "C is the low-level programming language taught in UMD's CMSC216 class. ==Usage== ==Memory Allocation== There are 3 ways to allocate memory in C * <code>malloc(bytes)</code> A...")
 
No edit summary
Line 2: Line 2:


==Usage==
==Usage==
==Memory Allocation==
===Memory Allocation===
<code>#include <stdlib.h></code><br>
There are 3 ways to allocate memory in C
There are 3 ways to allocate memory in C
* <code>malloc(bytes)</code> Allocated memory is uninitialized.
* <code>malloc(bytes)</code> Allocated memory is uninitialized.

Revision as of 20:22, 24 October 2019

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 automatically garbage collection, use C++ which has smart pointers.