1

I've been doing a little research on the security of strncmp and I understand it's not null terminated. But I've also seen how some people are saying it is "not a secure replacement for strcmp()." Could anyone explain this to me please? I've been looking for a while but really the only place i can find that says that is here on SO on a few questions. Maybe someone could link me a few resources for looking into this? Thanks.

Puma Pants
  • 11
  • 1
  • 1
    Welcome to Stack Overflow! Are you thinking of `strncpy`? `strncmp` does handle null-terminated strings properly. More generally, can you elaborate on what specific concerns you have, perhaps with some links or examples? – templatetypedef Jun 02 '20 at 18:49
  • Thanks! Im focusing mainly on strncmp as it relates to something im doing irl, i was mostly looking at these 2 posts https://stackoverflow.com/questions/24353504/whats-wrong-with-strcmp https://stackoverflow.com/questions/30190460/advantages-of-strncmp-over-strcmp Maybe I had my funcs mixed up with strncpy though, thanks for catching that. I was wondering what people meant when they said it wasn't a secure replacement for strcmp. i.e. >As I understand it, strncmp doesn't exist for "safety", but rather "I want to compare the first N characters of these strings". – Jonathon Reinhart Jun 22 – Puma Pants Jun 02 '20 at 19:00
  • sorry had to edit my comment – Puma Pants Jun 02 '20 at 19:04

1 Answers1

1

I think this thread might help you - Is there any safe strcmp?

In short, even though you can send in the size of the strings to be compared, strncmp will still read garbage values if the string is shorter than size 'n' and it is not null terminated.

Similar to your question - Why should you use strncpy instead of strcpy?

tikna
  • 34
  • 1
  • 3