0

Where we use malloc?

What is the purpose of use it

8th Apr 2019, 7:51 AM
Vicky
Vicky - avatar
5 Answers
+ 14
The function malloc is used to allocate a certain amount of memory during the execution of a program. The malloc function will request a block of memory from the heap. If the request is granted, the operating system will reserve the requested amount of memory. When the amount of memory is not needed anymore, you must return it to the operating system by calling the function free. Memory allocated via malloc is persistent: it will continue to exist, even after the program leaves the scope which called the allocation, until the program terminates or the memory is explicitly deallocated by the programmer. This is achieved by use of the free subroutine. Its prototype is void free(void *pointer); which releases the block of memory pointed to by pointer. pointermust have been previously returned by malloc, calloc, or reallocand pointer must not be used after it has been passed to free. In particular memory allocated via new or new[] should not be passed to free, and pointers which did not come from a malloc
8th Apr 2019, 10:07 AM
Keerthana
Keerthana - avatar
+ 3
Tqâ˜ș
8th Apr 2019, 6:56 PM
Vicky
Vicky - avatar
+ 3
To allocate Dynamic memory in both C & C++ we use stdlib.h library functions like malloc(), calloc(), realloc() & free(). The three function returns pointer of allocated datatype malloc(), calloc() and realloc(). If they failed to allocate memory they return NULL. e.g: 1) int *p=(*int)malloc(5*sizeof(int)); 2) struct book *p=(struct record*) calloc(10,sizeof(struct book)); //It is used to allocate array of user defined datatype. 3) //To increase the memory of allocated datatype we use realloc(). p=(int*) realloc (p,20); //Here p is pointer and 20 is new size. 4) If you allocate a memory don't forget to free it will affect your memory. So syntax for free is free(p); //here p is pointer. The C++ programming language also supports these functions; but it has new feature that is new and delete operators, provide similar functionality. e.g: node *ptr=new node; //to create a new node(may be a class or a struct datatype). delete(ptr); //to release the memory.
9th Apr 2019, 5:40 AM
Zaff's
Zaff's - avatar
0
thanks all 😁
3rd Jun 2020, 2:58 AM
Waled Moumari
Waled Moumari - avatar
0
Fill in the blanks to allocate memory for an array of strings of the size count, then remove it from memory. *arr = Type string[ Type Type
23rd May 2023, 3:24 AM
Pradhyumn Rathore