Hi,
Can anyone suggest any idea or some C code to implement malloc function. The point is how will you find the amount of memory present in the heap and allocate it.
Please try to explain the code as I am sure it would be complicated.
Thanks.
Printable View
Hi,
Can anyone suggest any idea or some C code to implement malloc function. The point is how will you find the amount of memory present in the heap and allocate it.
Please try to explain the code as I am sure it would be complicated.
Thanks.
Dynamic 2D array of longs:
Code:// Malloc returns a pointer to the beginning of the array you just initialised
// (long*) is a typecast telling the compiler that malloc is returning a pointer to an array of longs
long *pointer = (long*)malloc(length * width * sizeof(long));
if (pointer == NULL) {
// Do something error-like (malloc returns null if failed to allocate memory)
}
//From now on we can use it like a 1-dimensional array, use this formula to write a 2D position:
pointer[(y * width) + x] = value;
// When done, you MUST do this:
free(pointer);
Hi tigs,
Thanks for responding. However I think you didnt get my question. I want to know how is the malloc function actually written in the system library. I mean what would be the contents/definition of the function. How would the function figure out how much heap memory is remaining and how would it allocate it.
Thanks.
We are not allowed to know that...Quote:
Originally posted by rahuls
Hi tigs,
Thanks for responding. However I think you didnt get my question. I want to know how is the malloc function actually written in the system library. I mean what would be the contents/definition of the function. How would the function figure out how much heap memory is remaining and how would it allocate it.
Thanks.
It's up to each compiler.
>The point is how will you find the amount of memory present in the heap and allocate it.
You would use a system level function or other implementation/system dependent method to acquire core memory from the free store. malloc is one of the functions that will probably be wildly different for every system.
-Prelude
Here's how GNU did it.
gg