5,321
edits
(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...") |
|||
(One intermediate revision by the same user not shown) | |||
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. | ||
Line 9: | Line 10: | ||
Memory allocated by <code>malloc</code> and <code>calloc</code> are on the heap and should be deallocated by <code>free</code> when no longer used to avoid memory leaks.<br> | Memory allocated by <code>malloc</code> and <code>calloc</code> are on the heap and should be deallocated by <code>free</code> when no longer used to avoid memory leaks.<br> | ||
Memory allocated by <code>alloca</code> is allocated on the stack and will automatically be freed. Do not call <code>free</code> on this memory. Do not allocate more than a few bytes using <code>alloca</code> or you will risk a stack overflow leading to undefined behavior.<br> | Memory allocated by <code>alloca</code> is allocated on the stack and will automatically be freed. Do not call <code>free</code> on this memory. Do not allocate more than a few bytes using <code>alloca</code> or you will risk a stack overflow leading to undefined behavior.<br> | ||
For | For automatic garbage collection, use [[C++]] which has smart pointers. |