Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the size of a memory block allocated using malloc()? [duplicate]

Tags:

People also ask

How do you determine the size of allocated memory?

Q) How can you determine the size of an allocated portion of memory? In C language, we can calculate the size of the static array using the sizeof operator but there is no operator to calculate the size of the dynamically allocated memory.

How do I know my size after malloc?

To determine the size of data elements to be reserved by calloc or malloc in a machine-independent way, the sizeof operator should be used. The sizeof operator returns the size of the specified item in bytes.

What is the block size allocated by malloc () in this program?

The malloc() function reserves a block of storage of size bytes. Unlike the calloc() function, malloc() does not initialize all elements to 0. The maximum size for a non-teraspace malloc() is 16711568 bytes.

How can you tell the size of memory allocated by malloc using pointers?

ptr = (cast-type*) malloc(byte-size) For Example: ptr = (int*) malloc(100 * sizeof(int)); Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory.


Possible Duplicates:
How can I get the size of an array from a pointer in C?
Is there any way to determine the size of a C++ array programmatically? And if not, why?

I get a pointer to a chunk of allocated memory out of a C style function. Now, it would be really interesting for debugging purposes to know how big the allocated memory block that this pointer points is.

Is there anything more elegant than provoking an exception by blindly running over its boundaries?

Thanks in advance, Andreas

EDIT:

I use VC++2005 on Windows, and GCC 4.3 on Linux

EDIT2:

I have _msize under VC++2005 Unfortunately it results in an exception in debug mode....

EDIT3:

Well. I have tried the way I described above with the exception, and it works. At least while I am debugging and ensuring that immediately after the call to the library exits I run over the buffer boundaries. Works like a charm.

It just isn't elegant and in no way usable in production code.