B
Bert
I have a question about buffer overflows with strcmp or strncmp
(strnicmp). It's best described by providing an example
Example:
There is a string "sBuf" of length 5000. In a for loop from 0 to 5000,
several NUL terminated strings are compared, these strings vary in size
from 3 to 9.
sBuf is user input (a file), memory is dynamically allocated using
malloc (file length+1) and it is properly nul terminated. The other
strings are constants.
Do I need to check if the length of the string fits inside "sBuf"
before doing the compare or will strncmp automatically stop comparing
when it encounters a NUL character in sBuf?
If the character count of sBuf reaches 4998 and the string is of length
6, it would compare unallocated memory if it does not stop at sBuf's
NUL termination.
Because there are many strings to check, I can't simply limit the range
of the for loop to prevent a compare overflow. Checking before each
compare may slow down loops and it may cause bugs due to added
complexity.
Thanks for your answer.
Bert
(strnicmp). It's best described by providing an example
Example:
There is a string "sBuf" of length 5000. In a for loop from 0 to 5000,
several NUL terminated strings are compared, these strings vary in size
from 3 to 9.
sBuf is user input (a file), memory is dynamically allocated using
malloc (file length+1) and it is properly nul terminated. The other
strings are constants.
Do I need to check if the length of the string fits inside "sBuf"
before doing the compare or will strncmp automatically stop comparing
when it encounters a NUL character in sBuf?
If the character count of sBuf reaches 4998 and the string is of length
6, it would compare unallocated memory if it does not stop at sBuf's
NUL termination.
Because there are many strings to check, I can't simply limit the range
of the for loop to prevent a compare overflow. Checking before each
compare may slow down loops and it may cause bugs due to added
complexity.
Thanks for your answer.
Bert