29

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

sth
  • 222,467
  • 53
  • 283
  • 367
  • 9
    Ask yourself: How should strlen() know where your string ends, if it's not null-terminated? – DevSolar Mar 10 '09 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 :) – fredoverflow Oct 28 '11 at 16:37
  • Haev you considered consulting the documentation? – user207421 Sep 27 '20 at 03:22
  • If you know the buffer size, you might want to use [memchr](https://www.cplusplus.com/reference/cstring/memchr/) instead, which returns null pointer if no null terminator is found, or strnlen to cap the max size of string. – Phi Oct 23 '21 at 03:10

9 Answers9

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.

Hosam Aly
  • 41,555
  • 36
  • 141
  • 182
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.

MSN
  • 53,214
  • 7
  • 75
  • 105
5

May be You need strnlen?

vitaly.v.ch
  • 2,485
  • 4
  • 26
  • 36
2

Not really, and it will cause bad things.

Devin Jeanpierre
  • 92,913
  • 4
  • 55
  • 79
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.

EvilTeach
  • 28,120
  • 21
  • 85
  • 141
1

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

Roland Rabien
  • 8,750
  • 7
  • 50
  • 67
0

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

David Segonds
  • 83,345
  • 10
  • 45
  • 66
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 :)

Nik
  • 1,364
  • 8
  • 7
-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");
vitaly.v.ch
  • 2,485
  • 4
  • 26
  • 36