Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

How does that fixed upper bound on loops work? If there's an array of dynamic size that needs to be looped over, how do you do that?


I cant speak for NASA, but in general if you are writing extremely safety critical code you simply don't use dynamically sized things. In addition to safety, the dynamically sized objects cause issues for the real-time constraints on these system as well.


There are no dynamically sized arrays. All memory is allocated at startup and that's it.

This is the reason why you see power of two limits in safety critical software. For example "radar is able to track up to 256 simultaneous objects".

    for (i = 0; i < 256: i++) {
       if (NULL != object[i]) {
           // do stuff
       }
    }


#define MAX_NUM_OBJS 100

for(int i = 0; i < num_objs && i < MAX_NUM_OBJS; i++)

Combined with the no dynamic allocation rule, you can guarantee that the number of elements in the array must be less than some maximum since you have limited dedicated space for storing them.


There might not be a valid object at every location in the preallocated memory.

Say you have a list of visible satellites, and the number of them can change as they go in/out of view. There's never more than 100, but sometimes there's 50 and sometimes 60.

I supposed you could have an object with an INVALID flag, which the loop can use in its logic?


That's a good point. If you do have a situation where the number of objects is somewhat dynamic, you could use layers of protection such as (re)initializing the unused objects to a known safe state, adding a flag as you mentioned, adding sentinel values to the end, and at the very least you do have the guarantee that you aren't running off into memory that was actually dedicated to another purpose and contains fundamentally different data. If you are doing something really dynamic, you could embed two linked lists (or an embedded list and a free index stack or even two packed stacks). The reason for stacks over lists is that lists can accidentally become cycles.


My take on it is. If have a task that can only allocate `once` a area of memory for initialization, then you can use the allocation size to put a constraint on the iterators based on the datatype size.

eg...

  const size_t taskSize = 256;
  const Task *task = (Task*) malloc(taskSize);
  zeroMemory(task,taskSize);

  // Allocate array of int's
  int *intPtr = (int*)(task);
  int intSize = taskSize+4;

  for (int i=0; i<intSize && i<(taskSize/sizeof(int)); i++)
  {
  // do stuff.
  }


Agreed, this puzzled me as well. I also have thought it was curious that we didn't get dynamically sized arrays in C until C99. Before that you had to malloc to the heap. It makes a little more sense now though having read this.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: