30

Is strlen(const char *s) defined when s is not null-terminated, and if so, what does it return?

4
  • 9
    Ask yourself: How should strlen() know where your string ends, if it's not null-terminated? Commented Mar 10, 2009 at 20:50
  • 2
    Technically speaking, there is no such thing as a C string that is not NUL-terminated, because the NUL-Terminator is defined to be part of the C string :) Commented Oct 28, 2011 at 16:37
  • Haev you considered consulting the documentation? Commented Sep 27, 2020 at 3:22
  • If you know the buffer size, you might want to use memchr instead, which returns null pointer if no null terminator is found, or strnlen to cap the max size of string. Commented Oct 23, 2021 at 3:10

9 Answers 9

42

No, it is not defined. It may result in a memory access violation, as it will keep counting until it reaches the first memory byte whose value is 0.

Sign up to request clarification or add additional context in comments.

2 Comments

It can also cause demons to fly out your nose. catb.org/jargon/html/N/nasal-demons.html
That explains my aching nostrils.
12

From the C99 standard:

The strlen function returns the number of characters that precede the terminating null character.

If there is no null character that means the result is undefined.

Comments

5

May be You need strnlen?

2 Comments

Unfortunately, this isn't part of standard C.
strnlen() is not so helpful if we have no idea the 'real' buffer size of the const char *s size or maxi size
2

Not really, and it will cause bad things.

Comments

2

If your string is not NUL terminated, the function will keep looking until it finds one.

If you are lucky, this will cause your program to crash.

If you are not lucky, you will get a larger than expected length back, with a lot of 'unexpected' values in it.

Comments

1

It is not defined. It causes undefined behavior which means anything can happen, most likely your program will crash.

Comments

0

It will return the number of characters encountered before '\0' is found.

Comments

0

strlen() only works (does something useful) on null-terminated strings; you'll get an entirely undefined result if you pass in anything other than that. If you're lucky, it won't cause a crash :)

1 Comment

correction, if he is lucky it will crash. You wouldn't want this type of error to go unnoticed :-P.
-3

man 3 strcspn

size_t strcspn(const char *s, const char *reject);

A length of colon delimited strings:

size_t len = strcspn(str, ":");

A length of comma delimited strings:

size_t len = strcspn(str, ",");

A length of tab delimited strings:

size_t len = strcspn(str, "\t");

1 Comment

Doesn't answer the question in any way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.