0

I am required to convert all instances of strlen in our code base to the more secure version strnlen_s. The only difference between the two functions arguments is strnlen_s' requirement for the maximum length of the buffer you are providing.

This is a really straight forward process with instances of a character array (char array[64]) that have explicit lengths (sizeof(array)). Unfortunately, there are several instances of strlen being used with a character pointer (char*), whose size is always 8.

Is there a way to use strneln_s with character pointers?

  • If there was an easy way, you wouldn't need to make the conversion yourself in the first place. The hard part about doing what you are doing is specifically finding a way to get information on the size of the pointed array where it's used. – François Andrieux Feb 05 '20 at 18:48
  • I recommend refactoring to using `std::string` instead. – NathanOliver Feb 05 '20 at 18:51
  • @ewisjos It is very simple!:) just write strnlen_s( s, strlen( s ) + 1 ); :) – Vlad from Moscow Feb 05 '20 at 18:52
  • `Is there a way to use strneln_s with character pointers? ` Of course. The pointer points to an array. Pass the size of that array to `strnlen_s`. – eerorika Feb 05 '20 at 18:55
  • @VladfromMoscow that defeats the whole purpose of this exercise – Remy Lebeau Feb 05 '20 at 18:56
  • @eerorika the OP understands that, the question is about how to get that size when all that is available is a `char*` pointer – Remy Lebeau Feb 05 '20 at 18:57
  • @RemyLebeau The answer to that is you can't. The solution is to change the premise so that you have the length of the array available. – eerorika Feb 05 '20 at 18:58
  • @lewisjos are you able to change your functions that only have `char*` pointers to have `char(&)[]` references instead? For example `void func(char* p)` -> `template void func(char (&p)[size])`, then you would have the `size`. Otherwise, you would have to pass around the `size` explicitly: `void func(char *p, size_t size)`. Better would be to just refactor to use `std::string` everywhere, like NathanOliver suggested, then you can use `std::string::size()` – Remy Lebeau Feb 05 '20 at 19:00
  • for arrays you can do what you are doing, using sizeof. For char pointers, you need to come up with a maximum reasonable length. If you have a malloc for it around, you can use it's argument. – Serge Feb 05 '20 at 19:11
  • Whose idea was this anyway? `strnlen_s` serves no useful purpose that I can see. – Paul Sanders Feb 05 '20 at 19:28
  • @PaulSanders Calling `strlen` on an char array that isn't null terminated is UB. The reasoning behind `strlen_s` is that if you know the size of the array, you can avoid that. – François Andrieux Feb 05 '20 at 19:44

0 Answers0