impose restrictions on buffer size
Is there any
way I can impose a size constraint on a characte开发者_如何学Pythonr buffer such that no kind of operation on the buffer would lead to an out-of-bounds access?
In short: No
C does not perform any runtime checks, unless you do them by hand.
You could use your own functions, macros and per-buffer book-keeping to guard against invalid accesses. However, you would have to use this interface everywhere, which means that you would lose direct access to that buffer.
You would also see an impact on performance due to the extra condition checks. You might be able to avoid some of that by using direct access on code branches that are proven to not cause out-of bounds accesses.
EDIT:
There is also the rather major question of "what should the code do once an invalid access is detected". Should your program output an error and exit, as if it encountered an exception in other languages? Should it ignore the error? Should it attempt to fix it?
The C way to deal with this issue is to look-before-you-leap and ensure that each code branch/part is safe beforehand, rather than check each access.
This may help: http://duma.sourceforge.net/ in your quest.
The short answer: No.
The long answer:
To ensure even something as silly as buffer[ULLONG_MAX]
does not go out of bounds, you need to declare your buffer with a bound bigger than the biggest integer number representable on the system. This is obviously not possible, aside from the amount of memory that such a buffer would need.
The practical solution is that you manually keep track of the size of your buffer and any untrusted indexing into the buffer is verified against the buffer size.
See our Memory Safety Checker, which used as a debugging aid, instruments your C code to determine if you make any errors with arrays or buffers. This finds problems that valgrind cannot.
精彩评论