malloc in an embedded system without an operating system

前端 未结 3 1670
自闭症患者
自闭症患者 2021-02-08 02:47

This query is regarding allocation of memory using malloc.

Generally what we say is malloc allocates memory from heap.

Now say I have a

相关标签:
3条回答
  • 2021-02-08 03:17

    From the heap as you say. The difference is that the heap is not provided by the OS. Your application's linker script will no doubt include an allocation for the heap. The run-time library will manage this.

    In the case of the Newlib C library often used in GCC based embedded systems not running an OS or at least not running Linux, the library has a stub syscall function called sbrk(). It is the respnsibility of the developer to implement sbrk(), which must provide more memory the the heap manager on request. Typically it merely increments a pointer and returns a pointer to the start of the new block, thereafter the library's heap manager manages and maintains the new block which may or may not be contiguous with previous blocks. The previous link includes an example implementation.

    0 讨论(0)
  • 2021-02-08 03:37

    The only real answer is "Wherever your compiler/library-implementation puts it".

    In the embedded system I use, there is no heap, since we haven't written one.

    0 讨论(0)
  • 2021-02-08 03:40

    malloc() is a function that is usually implemented by the runtime-library. You are right, if you are running on top of an operating system, then malloc will sometimes (but not every time) trigger a system-call that makes the OS map some memory into your program's address space.

    If your program runs without an operating system, then you can think of your program as being the operating system. You have access to all addresses, meaning you can just assign an address to a pointer, then de-reference that pointer to read/write.

    Of course you have to make sure that not other parts of your program just use the same memory, so you write your own memory-manager:

    To put it simply you can set-aside a range of addresses which your "memory-manager" uses to store which address-ranges are already in use (the datastructures stored in there can be as easy as a linked list or much much more complex). Then you will write a function and call it e.g. malloc() which forms the functional part of your memory-manager. It looks into the mentioned datastructure to find an address of ranges that is as long as the argument specifies and return a pointer to it.

    Now, if every function in your program calls your malloc() instead of randomly writing into custom addresses you've done the first step. You can write a free()-function which will look for the pointer it is given in the mentioned datastructure, and adapts the datastructure (in the naive linked-list it would merge two links).

    0 讨论(0)
提交回复
热议问题