malloc in an embedded system without an operating

2019-03-19 08:59发布

This query is regarding allocation of memory using malloc.

Generally what we say is malloc allocates memory from heap.

Now say I have a plain embedded system(No operating system), I have normal program loaded where I do malloc in my program.

In this case where is the memory allocated from ?

3条回答
何必那么认真
2楼-- · 2019-03-19 09:30

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).

查看更多
3楼-- · 2019-03-19 09:38

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.

查看更多
劳资没心,怎么记你
4楼-- · 2019-03-19 09:40

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.

查看更多
登录 后发表回答