How "new" in C++ is working??

Hi

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..

Thanks..
Vijay
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.

3. I don't understand the question.

I completely agree with jsmith answers.

Just to add to smiths answers to 2/4 you can use the operating overloading concept of C++ to change the behavior of default new operator.

You need to rephrase your question 3.
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?
How would you allocate memory for the same object? Say you have a class/struct foo:

1
2
foo* a = new foo;
foo* b = new foo;

In this case, you'll have two separate objects of type foo. There's no "repeated allocation". Is this what you mean?
I think he means this:
1
2
3
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.
Topic archived. No new replies allowed.