strcmp/strncmp/strnicmp

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
 
R

Richard Bos

Bert said:
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?

Both strncmp() and (obviously) strcmp() will stop comparing when they
hit a null character.

Richard
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,983
Messages
2,570,187
Members
46,747
Latest member
jojoBizaroo

Latest Threads

Top