1. C語言strlen函數參數如果是NULL,則會出錯。
可以參考glibc中strlen的具體實現
通常使用前可以判斷一下參數是否是NULL,或者自己寫一個strlen的實現函數。
2. String Length
You can get the length of a string using the strlen function.
This function is declared in the header file string.h.
Function: size_t strlen (const char *s)
Parameters
s: pointer to the null-terminated byte string to be
examined
Return value
The length of the null-terminated byte
string str
The strlen function returns the length of the string s in
bytes. (In other words, it returns the offset of the terminating
null byte within the array.)
For example,
strlen ("hello, world")
12
3. glibc中strlen的實現在本地的測試
//============================================================================
// Name?: mystrlen.cpp
// Author?:
// Version?:
// Copyright?: Your
copyright notice
// Description : Strlen in C
https://github.com/lattera/glibc/blob/master/string/strlen.c
//============================================================================
#include
#include
#include
using namespace std;
#undef strlen
#ifndef STRLEN
# define STRLEN strlen
#endif
size_t STRLEN(const char *str) {
const char *char_ptr;
const unsigned long int *longword_ptr;
unsigned long int longword, himagic, lomagic;
for (char_ptr = str;
((unsigned long int) char_ptr & (sizeof(longword) - 1)) !=
0;
++char_ptr)
if (*char_ptr == '\0')
return char_ptr - str;
longword_ptr = (unsigned long int *) char_ptr;
himagic = 0x80808080L;
lomagic = 0x01010101L;
if (sizeof(longword) > 4) {
himagic = ((himagic << 16) << 16) | himagic;
lomagic = ((lomagic << 16) << 16) | lomagic;
}
if (sizeof(longword) > 8)
abort();
for (;;) {
//如果傳入的參數是空,此處會訪問崩潰,出錯
//原因:longword_ptr是NULL,則*longword_ptr無法訪問
longword = *longword_ptr++;
if (((longword - lomagic) & ~longword & himagic) != 0)
{
const char *cp = (const char *) (longword_ptr - 1);
if (cp[0] == 0)
return cp - str;
if (cp[1] == 0)
return cp - str + 1;
if (cp[2] == 0)
return cp - str + 2;
if (cp[3] == 0)
return cp - str + 3;
if (sizeof(longword) > 4) {
if (cp[4] == 0)
return cp - str + 4;
if (cp[5] == 0)
return cp - str + 5;
if (cp[6] == 0)
return cp - str + 6;
if (cp[7] == 0)
return cp - str + 7;
}
}
}
}
//測試代碼
int main() {
char *name = NULL;
int a;
a = strlen(name);//傳入的參數如果是NULL
return 0;
}