Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strlen not checking for NULL

Why is strlen() not checking for NULL?

if I do strlen(NULL), the program segmentation faults.

Trying to understand the rationale behind it (if any).

like image 306
hari Avatar asked Apr 26 '11 20:04

hari


People also ask

Does strlen check for null?

strlen(s) returns the length of null-terminated string s. The length does not count the null character.

Does strlen count blank spaces?

What is strlen() strlen() is a function to find the length of a string. It counts total characters which are presented in a string, eliminating the null character. The total number of characters in string includes, alphabets, special characters, and numbers, with blank spaces.

What is the length of a null string?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .

Can strlen fail?

Ok, I need to add some explanation. My application is getting a string from a shared memory (which is of some length), therefore it could be represented as an array of characters. If there is a bug in the library writing this string, then the string would not be zero terminated, and the strlen could fail.


1 Answers

The rational behind it is simple -- how can you check the length of something that does not exist?

Also, unlike "managed languages" there is no expectations the run time system will handle invalid data or data structures correctly. (This type of issue is exactly why more "modern" languages are more popular for non-computation or less performant requiring applications).

A standard template in c would look like this

 int someStrLen;   if (someStr != NULL)  // or if (someStr)     someStrLen = strlen(someStr);  else  {     // handle error.  } 
like image 74
Hogan Avatar answered Sep 19 '22 09:09

Hogan