I was wonder how malloc
would allocate memory (can you tell me ?), so I tried something.
Is this a bad way to allocate memory ?
void* myMalloc(unsigned int size) {
return (void*) new bool[size];
}
I was wonder how malloc
would allocate memory (can you tell me ?), so I tried something.
Is this a bad way to allocate memory ?
void* myMalloc(unsigned int size) {
return (void*) new bool[size];
}
The C++ standard states explicitely that the C malloc
and free
functions must not call operator new
or operator delete
(20.6.13/3 and 4 in the C++11 FDIS). This makes a red light blink in my mind...
Aside from that, your approach dumps all type-safety new
could give you that malloc
lacks. And your implementation will be too slow for what it does.
Conclusion: yes, this is a bad way to allocate memory.
The are some mistakes:
1) you're assuming sizeof(bool) == 1
, which is not necessarily true. Change the
return (void*) new bool[size];
to
return (void*) new char[size];
2) how will you free the memory? You'd have to do something like:
char* x = myMalloc(unsigned int size);
delete[] x; //not free, since you actually use new and not malloc
3) malloc
doesn't call new
, it's probably the other way around (in VS20xx new will call malloc
). malloc
also doesn't call the constructors, so if this does work, it will only work for basic types.
I hate to disagree with quite so many people recommending that you use new char[n]
, but I feel obliged to do so.
Since you want to allocate "raw" memory, not objects, you should really use ::operator new
instead of new some_type[some_size]
:
void *myMalloc(size_t size) {
return ::operator new(size);
}
Ultimately, new char[whatever]
isn't particularly harmful, but (at least IMO) it's conceptually wrong, and I see no advantage over using ::operator new
directly.
malloc()
/free()
is not necessarily compatible with new
and delete
. new
might very well invoke malloc()
(at least by default), but you shouldn't count on it.
One major difference between malloc()
and new()
is that malloc()
returns a void*
that points to raw memory, whereas new
returns a typed pointer and calls the constructor, if any (and delete
calls the destructor).
If you're writing C++, there is very rarely a good reason to allocate raw untyped memory.
But if you really want to do so, you can write something like:
void *p = (void*)new char[size];
If you want to allocate a certain number of bytes with new[]
, use new char[n]
. Unlike bool
, sizeof(char)
is guaranteed to be 1.
As to implementation of new
and malloc
, new
is a higher-level construct (as it also calls constructors for types that have those), and therefore likely implemented in terms of malloc
, not the other way round.