arcanex
arcanex

Reputation:

strlen() on non-null-terminated char string?

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

Upvotes: 30

Views: 41897

Answers (9)

vitaly.v.ch
vitaly.v.ch

Reputation: 2532

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");

Upvotes: -3

vitaly.v.ch
vitaly.v.ch

Reputation: 2532

May be You need strnlen?

Upvotes: 5

EvilTeach
EvilTeach

Reputation: 28882

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.

Upvotes: 2

Nik
Nik

Reputation: 1364

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 :)

Upvotes: 0

Devin Jeanpierre
Devin Jeanpierre

Reputation: 95606

Not really, and it will cause bad things.

Upvotes: 2

MSN
MSN

Reputation: 54634

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.

Upvotes: 12

Roland Rabien
Roland Rabien

Reputation: 8836

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

Upvotes: 1

David Segonds
David Segonds

Reputation: 84752

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

Upvotes: 0

Hosam Aly
Hosam Aly

Reputation: 42463

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.

Upvotes: 42

Related Questions