Reusing freed pointers in C

后端 未结 4 1912
臣服心动
臣服心动 2020-12-16 14:34

There are many questions on this website regarding freeing pointers after use and, further, setting them to NULL. Arguments are fierce and the topic is seemingly divided equ

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-16 15:12

    "Why would writing to a memory block that was previously freed, that still has the original pointer to it, cause the program to crash? -- See the first paragraph of the first post to the question linked above (if I missinterpreted the intent of this paragraph, please explain because it is not explicit on whether that pointer is used again to write the memory or a new pointer is created.)"

    I think reusing the same memory space after it has been free'ed is equal to 'crime', atleast for Kmem(slab allocation) based designs(I think mostly used in linux..correct me if I am wrong).

    To understand the reason we need to see how things work inside(you can skip and just read the conclusion at the end):

    1. OS divides the whole dynamically allocatable memory into pages. Each of these pages are assigned to hold objects(and a few for managing those objects and pages them sleves). One page can have objects of only one memory size. E.g. if the page size is 1024 bytes and the object that the page will be managing is 32 bytes. Then the whole page 'CAN' be divided into maximum of 1024/32 objects.

    In simple embedded systems, many pages in memory are divided into objects usually of size 2^y(e.g. 8 bytes, 16 bytes etc). So when you request z bytes of memory by malloc, where

    16 < z <=32

    The system returns one object from the pool of 32 byte objects held in some page having free objects. After assigning you this object, OS makes changes to the 'slab' data structure and marks the object at a given address as non-free.

    When you call free(), the object is returned to the slab pool as a free object and the OS can reassign it if other malloc call happens. This call can be made by your code or some other component running in the os.

    **So if you reuse the free'ed memory which the os had previously assigned to your code. Then you might be writing to some memory location which might be used:

    1. By your code OR
    2. Some other component running in the OS **

    Further, some other component who the OS re-assigned the pointer too could also over-write on your data.

    And this can cause severe data corruption.

    Further, make sure that you dont write more data to the memory, than what you requested through malloc(). Doing this can cause :

    1. Some other components data being corrupted
    2. Or Some memory management data structure being corrupted(like slabs, cache-managers etc).

提交回复
热议问题