5 ms·
In common user-space non-realtime environments only use arrays, if you have known bounds for the amount of elements. If an arbitrary number of elements is neede
by nuclx 8y ago
In common user-space non-realtime environments only use arrays, if you have known bounds for the amount of elements. If an arbitrary number of elements is needed, you need dynamic memory management anyways, so use linked lists. If your requirements prohibit malloc (at all or after initialization), you need to work with the available RAM as it suits your needs. Use fixed upper bounds, but check for full arrays and report errors, if array bounds are exceeded. This can be a bit of an art, especially when it comes to deciding what data to keep on the stack, in global arrays or on the heap as well as choosing approriate array sizes. Profile the RAM you need against what is available to you and optimize array sizes to make best use of the available RAM.
- mathieubordere 8y agoDynamic memory management in no way implies linked lists.
- nuclx 8y agoFair point. There are certainly other options like realloc'ing the memory for the array, if you want to keep constant time indexing.
- asdjw0efjlka 8y agoHe's a C programmer and they don't have generics, so they don't take advantage of vectors, but when you point this out they will display a macro hack or void* hack, then continue to use linked lists.
- nuclx 8y agoDid you see the OP ask any questions about C++?
- AlbertJWilliams 8y agoIs dynamic localization a valid and elegant solution or is it just an ugly hack? I want to use it but I also want to keep my code as flawless as possible (even if I'm still learning, I'd like to write high quality code).
- agitator 8y agoI assume you meant to say dynamic allocation? It depends on your application. If your application is fine with returning failed allocations and can handle the case, then it's okay. But if you have a real-time or safety critical system, for example, something running on a vehicle, robot, or flying device, you usually can't risk failed allocations. In that case the better bet is to reserve memory on the heap for your array and ensure that you are within bounds or within a certain threshold by checking on push data to your array or using a circular buffer. There are many approaches to solving a problem, and many ways to implement the solution, but the path you take usually depends on your application and your constraints. Think about which set of tradeoffs with respect to performance, safety, and memory usage makes the most sense for what you are trying to do.