Malloc
Function Signature
ptr = (cast_type *) malloc (byte_size);
Ways of pointer instantiation and declaration
All examples below construct the same pointer but are syntactically different and some contain superfluous code.
Memory allocation
int *pointer = malloc(sizeof int);
int *pointer = malloc(sizeof *pointer); // better
Note that it is slightly cleaner to write malloc statements by taking the size of the variable pointed to by using the pointer directly. If we later rewrite the declaration of ptr the following, then we would only have to rewrite the first part of it:
float *pointer;
/* hundreds of lines of code */
pointer = malloc(sizeof( *pointer));
Type casting
int *pointer = malloc(sizeof *pointer);
int *pointer = (int *)malloc(sizeof *pointer);
In C, you don't need to cast the return value of malloc. The pointer to void returned by malloc is automagically converted to the correct type. However, if you want your code to compile with a C++ compiler, a cast is needed.
Simultaneous declaration and instantiation
int pointer* = malloc(sizeof *pointer);
int pointer*;
pointer = malloc(sizeof *pointer); // slightly better?
The two statements do exactly the same. Some people suggest that the issue about initializing the result of malloc() is that the allocation may fail.
Recommendation: Subroutine for "safe-malloc"
The official GNU docs suggest writing a subroutine that calls malloc and reports an error if the value is a null pointer, returning only if the value is nonzero. This function is conventionally called xmalloc.
void *xmalloc(size_t size)
{
void *value = malloc(size);
if (value == 0)
fatal("virtual memory exhausted");
return value;
}
TL;DR
For this course, it's enough to declare a pointer and assign memory to it like so:
int pointer*;
pointer = malloc(sizeof *pointer);
More sources