1

When we do malloc(), the memory will be allocated and the base address is returned. If i call free(), it will frees the memory allocated by the malloc(). My doubt is that the number of bytes allocated by the free will be kept besides the baseaddress, the free() will check that number and frees the allocated memory. So will it possible to print that value (Number of bytes allocated).

user1808215
  • 273
  • 1
  • 6
  • 11
  • 5
    It is implementation dependent. If you take a look at your standard library's implementation, you can always try peeking at the datastructures involved, but *you are not supposed to*. So you can try it for science, but don't put this in production code. – Thomas Sep 20 '13 at 08:10
  • Read the source code of your allocator. For that, I suppose you first have to determine which allocator your library or your project uses (e.g. ptmalloc2, tcmalloc). You could also check GCC's `malloc.h` for some GCC-specific utility functions. Working with the internals of the allocation and deallocation is the core of heap-based code bug exploits, so there's plenty of "community interest", if you will. – Kerrek SB Sep 20 '13 at 08:13

3 Answers3

3

The application needs to keep track of the number of bytes allocated to a pointer and if this memory had already been free()ed again.

In C there is no portable way to retrieve the amount of memory allocated to a pointer via the pointer itsself.

alk
  • 69,737
  • 10
  • 105
  • 255
2

Even if it works, it will not be portable at all. The standard says nothing about this.

It is implementation dependent and you cannot rely on this.

Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
2

When you use malloc you get amount of memory you want or null pointer. So at that point you know number of bytes and you need to save it if you want to use it.

How malloc and free works depends on operating system. Each version of each OS could perform this operations differently.

Ari
  • 3,101
  • 2
  • 27
  • 49