简体   繁体   中英

Memory Management with pointers

I am developing a C library which has three functions. Init function takes a (void*) pointer to a memory chunk. I need to develop functions to allocate and deallocate memory blocks from that said chunk. What this means is that I have to keep track of which parts of the memory chunk I have allocated and which parts are free. Problem is, the structure I will implement to track the memory also has to be part of said memory chunk. I am not allowed to allocate new memory for my management structure.

And I have no idea how to do that.

Currently, I am planning to designate first few hundred bytes as header space and divide the rest into frames of equal size. I will use header space to create an array which will keep track of which frames are allocated. To do that, I need a way to convert memory address into long int so I can save them into the array and my search so far yielded nothing.

Is there any way to accomplish that? Failing that is there any other way to implement a management structure in this situation.

To do that, I need a way to convert memory address into long int so I can save them into the array and my search so far yielded nothing.

Is there any way to accomplish that?

Generally, you do not need to convert memory addresses to an integer type merely to keep track of them. Options include:

  • Work with pointers within the memory chunk you are given, using char * to perform arithmetic.
  • Subtract the base address of the memory (again with char * ) from pointers within it to get offsets of type ptrdiff_t (defined in <stddef.h> ) and use those.
  • Convert the addresses to the integer type uintptr_t (defined in <stdint.h> ). Unlike the other options, this has implementation-dependent behavior. In common C implementations, the result of conversion will be a simple memory address that you can perform arithmetic on as expected. But, in some C implementations, the result will be more complicated, so the code will not be fully portable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM