Question:
What is the use of malloc() function in C?
anonymous
2007-12-08 10:25:38 UTC
What is the use of malloc() function in C?
Four answers:
tfloto
2007-12-08 10:43:47 UTC
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);
ivanrj1975
2007-12-08 10:37:35 UTC
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.
paradox_dad
2007-12-08 10:37:53 UTC
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
anonymous
2014-03-12 15:01:06 UTC
malloc()

The name malloc stands for "memory allocation". The function malloc() reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form.



Syntax of malloc()

ptr=(cast-type*)malloc(byte-size)

Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...