Last active
December 18, 2015 09:28
-
-
Save Justasic/5761141 to your computer and use it in GitHub Desktop.
This shows how you can use pointer arithmetic to store the size of the allocated memory block in the pointer itself and use it to store how much memory is allocated. This does not include new[] or delete[] as well as malloc, calloc, realloc, free re-definitions (therefore the STL may allocate and use untracked memory)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <new> | |
#include <stdint.h> | |
#include <stdlib.h> | |
#include <cstdio> | |
#if 1 | |
// Define these as old ones | |
#define _new new | |
#define _delete delete | |
#undef new | |
#undef delete | |
size_t allocatedMemory; | |
void * operator new(size_t ptrSize) throw(std::bad_alloc) | |
{ | |
// Allocate a pointer as a size_t with enough space to store | |
// the amount of allocated memory needed.. | |
size_t *ptr = (size_t*)malloc(ptrSize+sizeof(size_t)); | |
// Debug | |
printf("Allocated pointer of size: %ld\n", ptrSize); | |
if(!ptr) | |
throw std::bad_alloc(); | |
else | |
{ | |
// Store the memory allocated in the ptr itself | |
*ptr = ptrSize; | |
allocatedMemory += ptrSize; | |
// Return the pointer + offset of the size to the real allocated memory | |
// the user intended. | |
ptr++; | |
return (void*) ptr; | |
} | |
} | |
void operator delete(void *allocatedPTR) throw() | |
{ | |
// Get the memory chunk size from the pointer | |
size_t *ptr = (size_t*)allocatedPTR; | |
ptr--; | |
size_t ptrSize = (size_t) *ptr; | |
allocatedMemory -= ptrSize; | |
printf("Deallocating pointer of size %ld\n", ptrSize); | |
// Make sure we correct the offset of the pointer before | |
// deallocating it | |
free(ptr); | |
} | |
#endif | |
struct reallyBig; | |
struct reallyBig | |
{ | |
char bigarr[(1 << 16)]; | |
struct reallyBig *somePTR; | |
double doubleDecker; | |
long long int veryLongInt; | |
struct reallyBig *bigArr[(1 << 16)]; | |
}; | |
int main() | |
{ | |
reallyBig *ptr = new reallyBig; | |
reallyBig *ptr2 = new reallyBig; | |
char *chr = new char; | |
*chr = 'H'; | |
ptr->veryLongInt = 10000000; | |
printf("Int: %lld\n", ptr->veryLongInt); | |
printf("Char: %s\n", chr); | |
printf("Total memory allocated: %ld\n", allocatedMemory); | |
delete chr; | |
delete ptr; | |
delete ptr2; | |
printf("Total memory allocated: %ld\n", allocatedMemory); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment