I reading about the memory management concepts. I want to know how these new, malloc and all working.
1. How they allocate memory in heap?
2. Is it possible to redirect the same to shared memory instead of heap?
3. how new or malloc is able to identify when a memory is created for same object?
4. Is it possible to change the behavior of shared memory to act like a heap memory? means when i call new/delete, memory should be allocated/deallocated in shared memory not is heap. how to achive this????
can any one help in this. or kindly share me some good links to refer..
1. new calls malloc. The implementation of malloc is not defined by the standard, but a common
implementation is for malloc to ask the kernel to allocate a large chunk of contiguous memory,
then malloc breaks it up into smaller pieces and puts pointers to the pieces into a hash table
(hashed based upon size of the piece).
2/4. You can write your own operator new either at class scope or in global scope that allocates
the memory in any way you want, including from shared memory.
Hi Vijay,
Was this the doubt you had in mind while framing Q.3 :
If we allocate a memory for an object say "obj1" using malloc/new, again if we allocate memory to same object "obj1" , will new/malloc be able to track this repeated allocation?
T *p;
p=new T;
p=new T; //"Repeated" allocation. In fact, this is a memory leak.
p is not an object, it's a pointer to an object. It's impossible to allocate memory for the same object twice, because then it's not the same object anymore.
Notice that with std containers you can overwrite the default memory allocator.
template < class T, class Allocator = allocator<T> > class deque;
In most cases we might do this.
std::deque<int> MyArray;
However we can certainly specify our own allocator as well as the value_type for each element of the container. A quick google search will turn up all kinds of articles on that subject.