top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the use of malloc() function in c language?

+3 votes
777 views
What is the use of malloc() function in c language?
posted Jan 25, 2016 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

We mainly use to allocate memory dynamically while execution of program.if you are familiar with linked list then you know that fact that we prefer linked list instead of array when we don't know size of data. its because in case of array we fixed the size but in case of linked list, we just use malloc() function and allocate memory whenever we require to store a value,address etc.
See an example:

struct node{
  int item;
  struct node *next;
} *head=NULL,*newnode=NULL;

int main(){
  // I am going to allocate memory dynamically using malloc()
  int ScannedValue;

  while(true) {   
   scanf("%d",&ScannedValue);
   // allotted memory as we are going to store a value inside newnode
   newnode=(struct node*)malloc(sizeof(newnode));
   newnode->item=ScannedValue;
   // as we connect nodes backward or forward and continue this process
  }
}
answer Feb 9, 2016 by Shivam Kumar Pandey
0 votes

This is a library function used to allocate memory dynamically within a process. Usually it is referred as heap memory. It's programmer responsibility to release the memory that was taken from the heap (using malloc).
prototype :
void *malloc(size_t len);
If it allocates memory successful then it returns valid address.
If it gets failed then it returns NULL.
Allocated memory may have garbage content so it is programmer responsibility to reset the memory content to avoid unpredictable behavior.

answer Jan 26, 2016 by Vikram Singh
...