?
=?ISO-8859-2?Q?Rafa=B3?=
Hi!
I would like to make my program know how much memmory it consumes at
runtime. At now I thought to do something like that:
/* test.cpp */
#include <cstdlib>
#include <stdio.h>
unsigned long long memory = 0;
bool makeout = false;
void* operator new[](size_t sz) {
void* m = malloc(sz);
if(m) {
memory += sz;
if (makeout) printf("Allocated by new[]: %i\n", sz);
}
return m;
}
void operator delete[](void* m) {
if (!m) return;
memory -= sizeof(m);
if (makeout) printf("Deallocated by delete[]: %i\n", sizeof(m));
free(m);
}
int main() {
memory = 0;
makeout = true;
int* p = new int[47];
delete [] p;
makeout = false;
}
/* End of file */
But of course it won't work fine becouse of "sizeof" used in delete[]...
The workaround I found is to make things like this:
void* operator new[](size_t sz) {
void* m = malloc(sz+4);
if(m) {
memory += sz+4;
*(unsigned int*)m = sz+4;
m = (char*)m+4;
if (makeout) printf("Allocated by new[]: %i\n", sz+4);
}
return m;
}
void operator delete[](void* m) {
if (!m) return;
m = (char*)m-4;
memory -= *(unsigned int*)m;
if (makeout) printf("Deallocated by delete[]: %i\n", *(unsigned int*)m);
free(m);
}
But this one makes a coast of 4 bytes on every allocation, which is not what
can satisfy me
Any suggestion welcome.
Thanks in advance,
Rafal
I would like to make my program know how much memmory it consumes at
runtime. At now I thought to do something like that:
/* test.cpp */
#include <cstdlib>
#include <stdio.h>
unsigned long long memory = 0;
bool makeout = false;
void* operator new[](size_t sz) {
void* m = malloc(sz);
if(m) {
memory += sz;
if (makeout) printf("Allocated by new[]: %i\n", sz);
}
return m;
}
void operator delete[](void* m) {
if (!m) return;
memory -= sizeof(m);
if (makeout) printf("Deallocated by delete[]: %i\n", sizeof(m));
free(m);
}
int main() {
memory = 0;
makeout = true;
int* p = new int[47];
delete [] p;
makeout = false;
}
/* End of file */
But of course it won't work fine becouse of "sizeof" used in delete[]...
The workaround I found is to make things like this:
void* operator new[](size_t sz) {
void* m = malloc(sz+4);
if(m) {
memory += sz+4;
*(unsigned int*)m = sz+4;
m = (char*)m+4;
if (makeout) printf("Allocated by new[]: %i\n", sz+4);
}
return m;
}
void operator delete[](void* m) {
if (!m) return;
m = (char*)m-4;
memory -= *(unsigned int*)m;
if (makeout) printf("Deallocated by delete[]: %i\n", *(unsigned int*)m);
free(m);
}
But this one makes a coast of 4 bytes on every allocation, which is not what
can satisfy me
Any suggestion welcome.
Thanks in advance,
Rafal