2

How does free() function work? We pass an only pointer on the first element of the array or string for free and this function "know" about the right border of allocated memory and freed it correctly. But why can't get this information from any C- standard functions?

Anton Golovenko
  • 634
  • 4
  • 19
  • 2
    This is implementation dependent. A common implementation is to have a block header preceding the data. That is, the header can be found by subtracting a fixed amount from the pointer returned by malloc. – kaylum Jan 25 '22 at 10:56
  • 2
    Please note that while such prefix blocks are common, if you attempt to access it from your application you're really going out of bounds of the memory area allocated by `malloc` and you will have *undefined behavior*. – Some programmer dude Jan 25 '22 at 10:57
  • 1
    https://stackoverflow.com/questions/6485586/code-for-malloc-and-free Check this answer, it contains links to malloc source code and description of it's work. When you know how the memory is allocated, you know how it can be deallocated. – Oleg Flores Jan 25 '22 at 11:07
  • 1
    And can you please elaborate on your question and your problem? Why do you need to get "this information"? Do you have an underlying problem that you think could be solved by that? Always please ask about your actual and underlying problems directly, it makes it easier to help you with them instead. – Some programmer dude Jan 25 '22 at 11:08

1 Answers1

1

Usually the allocated dynamically block of memory contains a prefix where the size of the allocated memory is stored.

So the function free can access this prefix to know the size of the deallocated block of memory.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335