I’m not sure what you mean by “correct”; your code is not correct at least in the sense mentione by @SamVarshavchik, and which a compiler will tell you about:
a.cpp: In function ‘int getFifoData(unsigned char*)’:
a.cpp:20:29: warning: ISO C++ forbids variable length array ‘tBuff’ [-Wvla]
uint8_t tBuff[txBuf.size()];
If you want to understand why C++ has no VLA’s read this SO question:
Why aren’t variable-length arrays part of the C++ standard?
Issues with the code
Here are some issues I believe you should consider.
Confusing names
- The function
readWrite()
– does it read? does it write? does it do both? Who knows. - Don’t clip names. If you want to name a buffer, call it
my_buffer
, notmy_buff
. Similarly,diagnostic_output
notdiagOutput
. - No impromptu initials. What’s a
tBuffer
? Is it a test buffer? A transaction buffer? A transmission buffer? A temporary buffer? - Not everyone knows what RX means.
getFifoData()
– what does it even do? Is its parameter a “FIFO”? That’s not what the parameter name says. And if it is – where is that information we supposedly get? There’s no destination buffer that’s passed for use, nor a container that’s returned.
Chance of buffer overflow / invalid memory access
- Why does
getFifoData()
take a buffer without also taking its length as well? - Better yet, why can’t it take a
span
?
Use of dynamically-allocated buffers
Both std::vector
and the variable-length array are dynamically-allocated memory. VLAs have their own issues (see link above), but as for vectors – you would be performing a memory allocation call on each call of this function; and that might be expensive if it gets called a lot.
Logging
Printing to the console or to a file is slow. Well, sort of slow, anyway – this is all relative. Now, this happens within an “if” statement, but if you’ve configured your app to log things, you’ll be paying this price on every call to getFifoData()
.
Time it!
Finally, – if you’re worried about performance, time your function, or do it with a profiler. Then you can see how much time it actually takes and whether that’s a problem.
solved Proper use of memory with dynamic array lengths in c++