Sunday, August 2, 2009

What is the use of malloc() function in C?

malloc is used to allocate memory from the heap. for example if you want an array of fifty integers:





int * array50 =(int *) malloc(50 * sizeof(int));





then you can use it as an array as long as you need it. for example:


array50[3] = 4; //assigns element 3 just like a static array.





the idea is that if your program only allocates memory while you need it you are free to use lots more memory instead of tying it up loads of memory with static declarations.








when you are done you use free


free(arrray50);

What is the use of malloc() function in C?
Since memory in a computer is a shared resource, when you need to use memory to store some data the program has to ask for memory, so the operating system can assign to your program certain segment of tha RAM memory.


Example:


malloc (30)


will assign to your process 30 bytes of memory. The operating system knows where in the memory is that segment, you only get a pointer to that address.





To ask for space for 50 integers:





int * a = (int *) malloc (sizeof(int) * 50);





and so on...


Bye.
Reply:malloc() allocates a block of memory on the heap and returns a pointer to the block.





When you use malloc(), you must later use free() to de-allocate the memory when it's no longer needed.





See http://en.wikipedia.org/wiki/Malloc


No comments:

Post a Comment