Do not cast the result of malloc (#20044)
https://stackoverflow.com/a/605858/3005749, also expanded the definition of heap
This commit is contained in:
committed by
Christopher McCormack
parent
a112fa501e
commit
11b1b150a8
@ -2,21 +2,21 @@
|
||||
title: malloc
|
||||
---
|
||||
# malloc in C
|
||||
malloc() is a library function that allows C to allocate memory dynamically from the heap. The heap is an area of memory where something is stored.
|
||||
malloc() is a library function that allows C to allocate memory dynamically from the heap. The heap is an area of memory that allows for dynamic storage which should be handled manually.
|
||||
|
||||
malloc() is part of stdlib.h and to be able to use it you need to use `#include <stdlib.h>`.
|
||||
|
||||
## Using Malloc
|
||||
malloc() allocates memory of a requested size and returns a pointer to the beginning of the allocated block. To hold this returned pointer, we must create a variable. The pointer should be of same type used in the malloc statement.
|
||||
malloc() allocates memory of a requested size and returns a pointer to the beginning of the allocated block. To hold this returned pointer, we must create a variable.
|
||||
Here we'll make a pointer to a soon-to-be array of ints
|
||||
```C
|
||||
int* arrayPtr;
|
||||
```
|
||||
Unlike other languages, C does not know the data type it is allocating memory for; it needs to be told. Luckily, C has a function called `sizeof()` that we can use.
|
||||
The result of the malloc will be automatically promoted to whatever pointer type we are using. Unlike other languages, C does not know which data type it is allocating memory for; malloc() simply knows how many bytes it should allocate. Luckily, C has a function called `sizeof()` that we can use.
|
||||
```C
|
||||
arrayPtr = (int *)malloc(10 * sizeof(int));
|
||||
arrayPtr = malloc(10 * sizeof(int));
|
||||
```
|
||||
This statement used malloc to set aside memory for an array of 10 integers. As sizes can change between computers, it's important to use the sizeof() function to calculate the size on the current computer.
|
||||
This statement uses malloc to set aside memory for an array of 10 integers. As sizes can change between computers, it is important to use the sizeof() function to calculate the size on the current computer.
|
||||
|
||||
Any memory allocated during the program's execution will need to be freed before the program closes. To `free` memory, we can use the free() function
|
||||
```C
|
||||
|
Reference in New Issue
Block a user