Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use strlen with scanf(%ms)

Is it possible to use strlen() over a dynamically allocated string?

FOR EXAMPLE:

#include <stdio.h>
#include <string.h>

int main ()
{
  char *input=NULL;
  printf ("Enter a sentence: ");
  scanf("%ms", &input);
  //Is this legit?
  printf ("The sentence entered is %u characters long.\n",(unsigned)strlen(input));
  return 0;
}
like image 956
Mattia Surricchio Avatar asked Dec 16 '25 19:12

Mattia Surricchio


1 Answers

You can use strlen() on any sequence of chars ended by a '\0' , the null-character aka NUL*1, which in fact equals 0.

It does not matter how the memory has been allocated.

So yes, this also applies to "dynamically allocated" memory.


*1: Not be mixed up with NULL, which is the null-pointer constant.

like image 189
alk Avatar answered Dec 19 '25 09:12

alk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!