Malloc is a function included in the standard C library. In C, this would be stdlib.h. In C++, this would be cstlib. It is used for manual memory allocation.
Use
malloc() is used to manually allocate space on the the heap. This is generally used for dynamic sizes of memory where the size of the thing to be allocated is unknown at compile time or the thing needs to have a lifetime exceeding the one of the function calling it.
Though be careful not to conflate dynamic memory allocation and dynamic data structures. Technically, variable length arrays can and are allocated on the stack all the time, whether in C or in C++ with vectors.
In C, the use of malloc is effectively necessary for proper dynamic memory allocation. In C++, it is generally better practice to use the keywords new and delete which are more idiomatic to C++.
Example
Malloc is generally used as follows:
void* malloc(size_t t);Malloc returns a void pointer, which in C does not explicitly need to be casted, but in C++ does. It is C-idiomatic to not cast the return value of malloc.
A void pointer is a pointer to an unknown type, effectively very similar to a typescript any. size_t is the return type of the sizeof() function, and literally represents the size in memory to be allocated.
The pointer returned by malloc points to the first byte in memory of that allocated space in memory. Malloc can fail, in which case it would return a null pointer.
Info
You will never need to check for failed allocation in either CPSC 213 or 221.
To prevent dereferencing the null pointer, check for null on malloc as so:
int* data = (int*) malloc(10 * sizeof(int));
if(data == null){
//handle failure
}If allocating 0 bytes in memory, behavior is implementation dependent and can possibly return a null pointer.
Initialization
Malloc does not initialize the memory it allocates, the contents of it are indeterminate upon allocation. To allocate and initialize memory to zero, use calloc() instead.
Warning
This is super important to understand. In many other programming languages, initializing a variable will initialize it to some default value, usually 0. This is not the case for C, and in some cases for C++. It will instead contain whatever random garbage it contained before. The exception to this in C are statically allocated variables.
Deallocation
To avoid memory leaks, i.e. that area in memory being used forever even after it’s use has passed, you need to deallocate that space in memory using [free]. Failing to do so will inevitably lead to a memory leak.
Reallocation
If the size of the malloc-ed object changes, use realloc(), which will attempt to expand or move the allocated memory while preserving its contents.