Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Pointer counter and overloaded new and delets to test memory allocation in c++
#include <ostream>
namespace pointer_counter {
std::size_t size_memory_register = 10;
void ** memory_register;
void init_memory_register() {
memory_register = (void **) std::malloc(sizeof(void *) * size_memory_register);
for (std::size_t record = 0 ; record < size_memory_register; record++) {
memory_register[record] = NULL;
}
}
void allocate_more_space_to_memory_register() {
// double size
std::size_t newsize = 2 * size_memory_register;
memory_register = (void **) std::realloc(memory_register, sizeof(void*) *newsize);
for (std::size_t record = size_memory_register ;
record < newsize; record++ ) {
memory_register[record] = NULL;
}
size_memory_register = newsize;
}
void addPointerToRegister(void * p ) {
std::size_t record = 0;
for ( ; record< size_memory_register; record++){
if (memory_register[record]==NULL) {
memory_register[record]=p;
break;
}
}
if (record==size_memory_register-1) {
allocate_more_space_to_memory_register();
addPointerToRegister(p);
}
}
void removePointerFromRegister(void * p ) {
std::size_t record = 0;
for ( ;record< size_memory_register; record++){
if (memory_register[record]==p) {
memory_register[record]=NULL;
}
}
}
std::size_t sizeRegister() {
std::size_t n_records=0;
for (std::size_t record=0; record < size_memory_register; record++) {
if ( memory_register[record] != NULL ) n_records++;
}
return n_records;
}
void reportRegister(std::ostream& out) {
for (std::size_t record = 0 ; record < size_memory_register; record++ ) {
if (memory_register[record] != NULL ) {
out << "Pointer " << memory_register[record] << " still allocated" << std::endl;
}
}
}
}
void * operator new (std::size_t to_allocate) {
// try to allocate size bytes
void * allocated = std::malloc(to_allocate);
pointer_counter::addPointerToRegister(allocated);
return allocated;
}
void operator delete(void* to_deallocate){
pointer_counter::removePointerFromRegister(to_deallocate);
std::free(to_deallocate);
}
void * operator new[] (std::size_t size){
void * p = malloc(size);
pointer_counter::addPointerToRegister(p);
return p;
}
void operator delete [] (void * p) {
pointer_counter::removePointerFromRegister(p);
free(p);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment