2

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;
}
alk
  • 69,737
  • 10
  • 105
  • 255
Mattia Surricchio
  • 1,362
  • 2
  • 21
  • 49
  • 3
    Will the string be properly terminated? Then yes you can use any string functions. And remember that the format `"%ms"` is a non-standard (and therefore non-portable) extension. – Some programmer dude Aug 05 '18 at 10:30
  • @Someprogrammerdude Yes the string is always properly terminated, i'm not worried about portability anyway – Mattia Surricchio Aug 05 '18 at 10:31
  • Just so you know, even if you're not doing portable things for the current program, learning non-portable features leads to bad habits that can come and bite you in the rear once you must use a different compiler or write portably. – Some programmer dude Aug 05 '18 at 10:33
  • @Someprogrammerdude Thank you for the advice! I'm aware of that, but i'm working on a school project not so well organised. They're almost forcing us to write orrible code... – Mattia Surricchio Aug 05 '18 at 10:40
  • 2
    Note: You can avoid the cast and use `%zu` if you use C99+ – Spikatrix Aug 05 '18 at 10:57
  • @someprogrammerdude: The `m` modifier is defined by [Posix](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fscanf.html), which is definitely a standard. Or are you saying that Posix functions should never be used? If so, how do you suggest one approaches sockets? :-) – rici Aug 05 '18 at 15:20
  • 1
    @rici Defined by *a* standard, not defined by *the* standard: The C standard. And as such, it is unportable and an extension to the C language. :) And the same goes for sockets really, it just happens to be that most other platforms emulate *parts* of the POSIX socket API. – Some programmer dude Aug 05 '18 at 15:25

1 Answers1

6

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.

alk
  • 69,737
  • 10
  • 105
  • 255