Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are stack allocations RT?

If I allocate something on the stack, is the allocation deterministic (i.e. RT)? Allocation example:

std::vector<double> desiredMobileState(13, 0.0);

I mean allocating on the heap requires a system call (in the general case) which is non-deterministic hence should be banned for a RT behavior.

But what happens with stack allocations in terms of RT behavior?

like image 278
arennuit Avatar asked Jul 11 '26 21:07

arennuit


2 Answers

The std::vector object itself is stack-allocated, but the object merely consists of pointers to a heap-allocated data array. (Of course, the C++ standard never uses the words "stack" nor "heap"; the above sentence is merely the usual implementation.) So allocating a vector with capacity 13 will almost certainly involve a heap allocation.

However,

allocating on the heap requires a system call (whatever the system)

is not necessarily the case. Most heap allocations do not require any interaction with the system. It is true that on most systems some heap allocations require a system call (to modify virtual memory maps), so they cannot be considered real-time, but it is quite possible to imagine a non-virtual-memory-based embedded system in which applications had fixed memory allocations and malloc either hands off part of that memory or fails. [Note 1]

You could use a custom allocator which allocated memory regions from a pre-reserved pool, but in order to guarantee RT you would need to also ensure that the pre-reserved pool was memory-resident.


Notes.

  1. Or you could just remember DOS/Apple; no need for a vivid imagination.
like image 82
rici Avatar answered Jul 13 '26 13:07

rici


This is all implementation-defined, of course, but in general the stack allocation itself is just the adding of a constant value to the stack pointer, so that is as deterministic as adding a value to an integer variable would be.

There are other operations that typically happen in concert with the stack allocation, however, which might make its timing non-deterministic. Specifically:

  • The running of a constructor routine to initialize the allocated object (and the constructor could of course do anything, depending on what the author of the class in question wrote there... e.g. it could allocate heap memory, open and read a file, go into an infinite loop, etc)
  • The writing to (and/or reading from) of the newly allocated stack memory, which could cause a page fault, if that area of memory wasn't already mapped in to physical RAM.
  • And, of course, there is always the possibility of a stack overflow, which might cause a segmentation fault (if you're lucky), or just random undefined behavior and chaos (if you're not so lucky).
like image 34
Jeremy Friesner Avatar answered Jul 13 '26 12:07

Jeremy Friesner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!