3

How to get the size of memory allocated dynamically?

 2 years ago
source link: https://www.codesd.com/item/how-to-get-the-size-of-memory-allocated-dynamically.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to get the size of memory allocated dynamically?

advertisements

Allocating memory dynamically using malloc will return the address from where the memory is allocated. Before that address meta-data is stored; it's a struct.

struct malloc_chunk {
    int      prev_size;
    int      size;           // size of memory allocated
    struct malloc_chunk* fd;
    struct malloc_chunk* bk;
    struct malloc_chunk* fd_nextsize;
    struct malloc_chunk* bk_nextsize;
};

I want to print value of size without using malloc_usable_size(). I tried but I am getting a segfault. I am working on 64-bit Ubuntu.


The structure is implementation dependent. You should not use the information at all since it might change at the next compiler or even at the next compiler version.

You should manage the size of memory in user defined structures.

Edit: Memory allocation algorithms usually work with some alignments to

  • avoid unaligned addresses in further allocations
  • provide best performance on architectures where unaligned access is allowed but could result in performance penalties
  • reduce the heap fragmentation be using chunks that are a multiple of a base, e.g. 16 bytes.

Therefore malloc doesn't need to allocate exactly the size that you passed as parameter. It can allocate a chunk the is sufficient to hold the requested size but probably more. It's not necessary for mallocto store the original value, only the chunk size is necessary to free the chunk.

Therefore it's probably impossible to retrieve the size parameter passed in the malloc function call.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK