Re: Customize operator new / delete
On May 8, 11:44 am, "io_x" <a...@b.c.invalid> wrote:
"Nephi Immortal" <immortalne...@gmail.com> ha scritto nel messaggionews:e=
557f572-1a34-4a96-aad9-ffd1241a71be@c41g2000yqm.googlegroups.com...
I decide to customize my own operator new and operator delete in the
global scope. They are independent outside class as long as they are
not function members of any class.
Please confirm if my code is valid as C++ standard states. I had
examined across website via google search. I only find user-defined
classes, but not for global scope.
#include <stdio.h>
#include <malloc.h>
for the C language the header of malloc() function is not malloc.h
but stdlib.h; possiblily you not call the malloc() of the C language...
inline
void *operator new( size_t size ) { return malloc( size ); }
inline
void *operator new[]( size_t size ) { return malloc( size ); }
this should be wrong because the right malloc size here is
malloc(size*sizeof(*pointerType))
but who know how to get the number sizeof(*pointerType)?
No, you are wrong unless you don't need to put sizeof() on malloc()
function inside operator new function because size_t size parameter of
operator new function is already provided the sizeof( type ) times
elements by C++ Compiler.
Test it yourself until you find out. You will always need to use
sizeof() if you place malloc() function somewhere.
inline
void operator delete( void *pUserData ) { free( pUserData ); }
inline
void operator delete[]( void *pUserData ) { free( pUserData ); }
int main()
{
char *p = new char[ 100 ];
here you are lucky for delete but what about
int *p = new int[ 100 ];
if is call the new above it reserve space for one
array of 100 chars not one array of 100 ints
The buffer overruns NEVER happens because C++ Compiler knows the
size. It will recognize int type and add four bytes each element in
the int array.
delete [] p;
i never understand that; excuse if i speak too much
return 0;
}- Hide quoted text -
- Show quoted text -