开发者

Removing Dynamic Memory Allocation - from a embedded C program

开发者 https://www.devze.com 2023-03-09 23:02 出处:网络
I\'m trying to port a C library to a embedded platform (Xilinx Microblaze), and the library contains some calls to malloc(), alloc(), calloc() and free().

I'm trying to port a C library to a embedded platform (Xilinx Microblaze), and the library contains some calls to malloc(), alloc(), calloc() and free().

These functions calls requite additional libraries to be imported in to the embedded platform, and will make the program code larger.

What's the best steps to take to remov开发者_Go百科e dynamic allocation from a C program, and only use static allocation. What are the facts i should find out, what calculations should i make ? Any tips are welcome.

example of malloc call:

   decoder->sync = malloc(sizeof(*decoder->sync));
     if (decoder->sync == 0)
       return -1;

Many Thanks,

Rosh


There are two issues to deal with when converting dynamic memory allocations (runtime) to static allocations (compile time). First, the compiler obviously has to know how much memory to allocate at compile time. In your example above it looks like whatever decoder->sync points to is a constant size, so it shouldn't be a problem. If you were allocating memory for a byte array for a variable length data sequence, though, you would have a problem. You would either have to allocate enough for the maximum possible data length, or break the data up into chunks, or... hopefully you get the idea.

The other issue is heap vs. stack. All dynamic memory allocations come from the heap. Non-global static memory allocations come from the stack, and stacks can be pretty small in embedded environments. This means that if the memory allocation is medium-to-largeish, you will probably need to make it global or "static" (locally scoped static variables also come out of the heap) to avoid stack overflow, even if the variable would not otherwise need to be global.

Hope this makes sense.

0

精彩评论

暂无评论...
验证码 换一张
取 消