Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

People also ask

Does strlen work without null?

According to standard, since your "string" does not have null terminator, this is not a string. Calling strlen with anything but string is undefined behavior, so anything can happen including the case you're observing.

What happens if a string is not null-terminated?

Many library functions accept a string or wide string argument with the constraint that the string they receive is properly null-terminated. Passing a character sequence or wide character sequence that is not null-terminated to such a function can result in accessing memory that is outside the bounds of the object.

Can you use strlen on char *?

The strlen() accepts an argument of type pointer to char or (char*) , so you can either pass a string literal or an array of characters.

What does strlen return for a null string?

1) Returns the length of the given null-terminated byte string, that is, the number of characters in a character array whose first element is pointed to by str up to and not including the first null character. The behavior is undefined if str is not a pointer to a null-terminated byte string.


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.


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.


May be You need strnlen?


Not really, and it will cause bad things.