I dint understand the concept of malloc Function..?
I dint understand the concept of malloc Function..?
EmbLogic Research & Competency Development Labs
Phone: +91 9818467776, 8527567776, 9650467776
Email: info@emblogic.com
Copyright © EmbLogic Embedded Technologies Pvt. Ltd.
malloc (memory allocation) is used to dynamically allocate memory from the heap at run time.
eg.
The simplest way to reserve memory is to code something like:
main()
{
char string[1000];
strcpy (string, “some text”);
}
The example above has two problems:
If the data is less than 1000 bytes we are wasting memory.
If the data is greater than 1000 bytes the program is going to crash.
The 1000 bytes are reserved throught out the life of the program. If this was a long running program that rarely used the memory, it would again be wasteful.
so we use malloc()
malloc allows us to allocate exactly the correct amount of memory
Library: stdlib.h
Prototype: void *malloc(size_t size);
Syntax: char * String;
String = (char *) malloc(1000);
Looking at the example syntax above, 1000 bytes are reserved and the pointer String points to the first byte. The 1000 bytes are NOT initialized by malloc. If the memory is NOT available, a NULL pointer is returned.
the cast is required to return a pointer of the correct type.