Jump to content
OMRON Forums

Dynamic Memory Allocate Problem


Recommended Posts

Hello Everyone!

Recently I wrote a small matrix in c for specific calculation in my project,but

I found I the user-written servo algorithm didn‘t work when I called function "malloc",for example,double* p = (double*)malloc(10*sizeof(double)),to allocate memory.

I just want to kown if PowerPmac forbid memory allocation for security or I need do something more?

Thank you.

Link to comment
Share on other sites

  • Replies 4
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic



User servo code runs in the kernel, so you need to use kmalloc instead of malloc to allocate memory on the heap. However, for something small like 10 doubles, you can easily allocate on the stack instead:


On the stack:
 double doubleArray[10];
 double *p = &doubleArray[0];
On the heap:
 double *p = kmalloc(10 * sizeof(double), GFP_KERNEL);


If you want to learn more about the available flags that can be passed to kmalloc, see table 11.5 in the following link: http://www.makelinux.net/books/lkd2/ch11lev1sec4

Link to comment
Share on other sites

Also, if you use kmalloc make sure that you aren't calling it every time the servo code executes. You will quickly use up all available memory and crash the processor. It is probably better to use the stack in this case (see previous post), or allocate memory on your first execution only.


If you have to kmalloc each time the servo code runs, make sure to call "kfree()" at the end of your servo code.

Link to comment
Share on other sites

Thank you so much shansen!


I just took “double* p = (double*)malloc(10*sizeof(double))” as an example to demonstrate I could not use function malloc,actually I wrote a small matrix library for specific calculation in which I need frequently allocate memory.However,thanks to your explanation and your advice,I decide to define array on the stack to store the value for matrix operation.In this way I can avoid dynamic

memory allocation,for I don't kwon much about linux.

Thank you again shansen!

Link to comment
Share on other sites



Shansen is correct. I prefer that when dealing with realtime processes not to dynamically allocate memory. The RTI thread is a hard realtime thread in the xenomai kernel memory space and scheduler. Code in here should be written carefully and kept tight and deterministic.


Another method you can try is to statically allocate global variables. I believe it is more efficient to do this, especially on large arrays and when you need persistence across multiple function calls.




//Some Large Array
double doubleArray[1024];

void realtimeinterrupt_plcc()

Link to comment
Share on other sites

This topic is now closed to further replies.

  • Create New...