The prototype of malloc function is:
void* malloc(size_t);
Malloc allocates a block of memory from the heap. The number of bytes that it allocates is given by its single argument and it returns pointer to void. If the memory is not available, the NULL is returned.
Malloc does not clear or modify the memory so the content of allocated memory should be treated as garbage.
The single argument of this function is of type size_t. If you pass a negative number to the argument, it can return a NULL value on some systems. If you pass a zero as a parameter, it might return a pointer to NULL or a pointer to a region with zero bytes allocated.
In 42 we commonly use malloc as follows:
int *ptr;
ptr = (int *)malloc(sizeof(int));
When we use a malloc, we should immediately check if malloc did not return a NULL value (in case that malloc is not able to allocate memory). We can check this with the condition as follows:
if (!ptr)
return (0);
This happens when we execute malloc:
- Malloc allocates memory from the heap,
- The allocated memory is not modified or cleared,
- The first byte’s address of allocated memory is returned.
Operator sizeof
We use sizeof operator to specify the number of bytes that we want to allocate for data type. For example if we want to allocate the memory from the heap for 5 integers we can do it as follows:
ptr = (int *)malloc(5 * sizeof(int));
Determining the amount of allocated memory
There is a maximum size that can be allocated with malloc. Its value depends on the system. When you look at the prototype of the function malloc, you suppose that the limit is defined by maximum possible value of size_t. However there can be other limitations such as the amount of physical memory present or other operating system constraints.
Some operating systems use “lazy initialization”. It means that malloc does not allocate the requested amount of the memory immediately as it is supposed to do when executed. What happens in this case is that malloc does not allocate the memory till the moment it is accessed. This is quite rare initialization schemes so probably you won’t encounter this behavior. However if so, there can arise a problem if there is not enough memory available to allocate.
Using malloc with static and global variables
It is not possible to use malloc with static or global variables as in the following example:
static int *ptr = (int *)malloc(sizeof(int));
It would generate compile-time error message. We must do as follows:
static int *ptr;
ptr = (int *)malloc(sizeof(int));
There is a diffrence between using the initialization operator “=” and using the assignment operator “=” from the compiler standpoint.
SOURCES:
[1] Understanding and Using C Pointers by Richard Reese (O’Reilly). Copyright 2013 Richard Reese, Ph.D. 978-1-449-34418-4