This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: why there is no memlen();


Hi Arun,

>is there any way to get the amount of memory allocated to a pointer.

Depends entirely on your heap manager.

For example, one platform that I worked on, you could do this:

typedef unsigned char byte;
struct MemChunk {
unsigned long length; // 32-bit
byte data[1]; // stretchy buffer
};

unsigned long GetMemLength(void* p) {
if(p == NULL) return 0;
struct MemChunk* mem = (struct MemChunk*)((byte*)p - sizeof(unsigned long));
return mem->length;
}


void Test() {
void* p = malloc(1000);
printf("%ld allocated\n", GetMemLength(p));
free(p);
}

However, this trick is VERY platform (OS + Compiler) specific.

I'm not sure what GCC uses. Even if something akin to the above works for GCC, it may be OS specific and/or version specific! Caveat emptor!

--Eljay


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]