I'm trying to have a better understanding of memory allocation in c++. There are many concepts and theories on webs but I can't find the source code of what's really in c++ global operator new.
I understand to simply overload operator new and delete I can just do this:
void* operator new(size_t size){
void* allocated = malloc(size); //allocate necessary space;
return allocated;
}
void operator delete(void* ptr){
SA<T>* p = static_cast< SA<T>* >(ptr);
return free(p);
}
But when I just saw some code overloaded operator new without using the new and delete keyword, I didn't know what was going on. The code I read is this:
#include <stddef.h>
struct Head {
long length;
struct Head *next;
) ;
static Head pool = { 0, 0 };
static Head *h = (Head *)HEAP_BASE ADDRESS;
/* fast dumb first-fit allocator */
typedef char *Char_p;
// NEXT LINE IS MACHINE AND COMPILER DEPENDENT:
const long WRDSIZE = sizeof (void*) ;
void* operator new(size_t nbytes)
{
/* First, look in free list */
if (pool.next){
Head *prev &pool;
for (Head *cur = &pool; cur; cur = cur->next) {
if (cur->length >= nbytes) {
prev->next - cur->next;
return (void*) (Char_p(cur) + sizeof(Head));
}else prev = cur;
}
}
/* Nothing on free list, get new block from heap */
h = (Head*) (((int) ((Char_p(h)+WRDSIZE-1))WRDSIZE)*WRDSIZE);
h->next = 0;
h->length = nbytes;
h = Char_p(h) + nbytes + sizeof(Head);
return (void*) (Char_p(h) - nbytes);
}
Not a single new or malloc was called. How can this allocate memory??