The ones who are crazy enough to think they can change the world are the ones who do.
- Steve Jobs

C Malloc()

Why Malloc?

Now it's time to partition the microprocessor's memory to your 6 teams of your startup company, If you want to allocate contiguous memory location to every team, then malloc() will help you out there.

malloc in c

What is Malloc?

  • malloc() is the programmer's shorthand to represent memory allocation.
  • malloc() allocates a block of size bytes to a program from the heap.
  • malloc() allocate an exact quantity of memory explicitly to a program, when required.
  • allocation of memory is done in contiguous location.

Syntax - Malloc()

Syntax
void *malloc  (size_t size);

C program - without using malloc() for unknown data

In the following program we will consider that we want to store two integer data , but unfortunately we are forced to store 4 integer data, but we allocated an array of size 2. Let us see what happen when we add 4 integer data in an array whose size is 2.

malloc-1.c
#include <stdio.h>
int main()
{
int numbers[2], i;
numbers[0] = 0;
numbers[1] = 1;
numbers[2] = 2;
numbers[3] = 3;
printf("\nStored integers are ");
for(i = 0; i < 4; i++)
printf("\nnumbers[%d] = %d ", i, numbers[i]);
return 0;
}
  • numbers[0] = 0
  • numbers[1] = 1
  • numbers[2] = 4132608
  • numbers[3] = 4132610

C program - using malloc() for unknown data

Let us redesign the above program using malloc() instead of array because when a memory is allocated either by using malloc() or calloc() inbuilt function, it can be reallocated using realloc() inbuilt function when some memory is demanded.

malloc-2.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *numbers = (int*)malloc(4* sizeof(int));
int i;
numbers[0] = 0;
numbers[1] = 1;
numbers[2] = 2;
numbers[3] = 3;
printf("\nStored integers are ");
for(i = 0; i < 4; i++)
printf("\nnumbers[%d] = %d ", i, numbers[i]);
return 0;
}
  • numbers[0] = 0
  • numbers[1] = 1
  • numbers[2] = 2
  • numbers[3] = 3

Note:

Programmer might thinks that malloc() is initialized at the beginning itself, then why array should not. Simply, malloc() is capable of reallocation i.e.) extending its size. But unfortunately array can't be reallocated. Please check realloc to clear all your doubt's in memory allocation.

Did You Know?

Once a block memory is allocated by using malloc() inbuilt function. Each individual blocks of memory are represented by some garbage value.

Report Us

We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.

Report