5,332
edits
No edit summary |
No edit summary |
||
Line 4: | Line 4: | ||
===Memory Allocation=== | ===Memory Allocation=== | ||
<code>#include <stdlib.h></code><br> | <code>#include <stdlib.h></code><br> | ||
There are | There are 2 primary ways to allocate memory in C: | ||
* <code>malloc(bytes)</code> Allocated memory is uninitialized. | * <code>malloc(bytes)</code> Allocated memory is uninitialized. | ||
* <code>calloc(number, bytes)</code> Allocated memory is initialized to 0. Allocates (number * bytes) bytes of memory. | * <code>calloc(number, bytes)</code> Allocated memory is initialized to 0. Allocates (number * bytes) bytes of memory. | ||
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. | |||
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.< | |||
{{ hidden | <code>_malloca</code> | | |||
There is also a way to allocate memory on the stack. | |||
* <code>alloca(bytes)</code> Usage is [https://stackoverflow.com/questions/1018853/why-is-the-use-of-alloca-not-considered-good-practice Discouraged] | |||
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 automatic garbage collection, use [[C++]] | For automatic garbage collection, use [[C++]] smart pointers or Rust instead. | ||
On Windows you also have: | On Windows you also have: | ||
* <code>_malloca</code> | * <code>_malloca</code> |