Checking if something was malloced

后端 未结 8 676
面向向阳花
面向向阳花 2021-01-12 07:06

Given a pointer to some variable.. is there a way to check whether it was statically or dynamically allocated??

8条回答
  •  借酒劲吻你
    2021-01-12 07:16

    Quoting from your comment:

    im making a method that will basically get rid of a struct. it has a data member which is a pointer to something that may or may not be malloced.. depending on which one, i would like to free it

    The correct way is to add another member to the struct: a pointer to a deallocation function.

    It is not just static versus dynamic allocation. There are several possible allocators, of which malloc() is just one.

    On Unix-like systems, it could be:

    • A static variable
    • On the stack
    • On the stack but dynamically allocated (i.e. alloca())
    • On the heap, allocated with malloc()
    • On the heap, allocated with new
    • On the heap, in the middle of an array allocated with new[]
    • On the heap, within a struct allocated with malloc()
    • On the heap, within a base class of an object allocated with new
    • Allocated with mmap
    • Allocated with a custom allocator
    • Many more options, including several combinations and variations of the above

    On Windows, you also have several runtimes, LocalAlloc, GlobalAlloc, HeapAlloc (with several heaps which you can create easily), and so on.

    You must always release memory with the correct release function for the allocator you used. So, either the part of the program responsible for allocating the memory should also free the memory, or you must pass the correct release function (or a wrapper around it) to the code which will free the memory.

    You can also avoid the whole issue by either requiring the pointer to always be allocated with a specific allocator or by providing the allocator yourself (in the form of a function to allocate the memory and possibly a function to release it). If you provide the allocator yourself, you can even use tricks (like tagged pointers) to allow one to also use static allocation (but I will not go into the details of this approach here).

    Raymond Chen has a blog post about it (Windows-centric, but the concepts are the same everywhere): Allocating and freeing memory across module boundaries

提交回复
热议问题