differences between malloc and operator new..

M

Matthias =?ISO-8859-1?Q?K=E4ppler?=

For example, if you want to track memory allocations. I have seen custom
implementations of new and delete which worked like this:

1) Create a class MemInfo which holds information about the memory and data
type you're about to allocate.

2) When new is called: Instantiate MemInfo with type T and store it right
before the object you actually want to create on the heap. Move the address
pointer by sizeof(mem_obj). Allocate space for the actual object and store
it. Return its address.

3) When delete is called: Analogous to 2), but vice versa (deallocate,
subtract sizeof(mem_inf) from address pointer, deallocate mem_inf and
return.
 
M

Matthias =?ISO-8859-1?Q?K=E4ppler?=

Thanks for the heads up, haven't been reading in that book for quite a time
now :)
 
O

Old Wolf

Gianni Mariani said:
I suspect that Scott Meyers says you should never do this :

T * t = (T*) malloc( sizeof( T ) ); // C style dynamic allocation

The example above is how you would normally do in C what "new" does in
C++. You should allways use new/delete in C++.

The above code is bad C as well as bad C++. In C you should write:
T *t = malloc(sizeof *t);

Casting the return value of malloc has no benefits whatsoever in C,
and it has some negatives (eg. it can cause compilers to suppress
the warning that you are invoking undefined behaviour by calling a
function without a prototype).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,150
Latest member
MakersCBDReviews
Top