加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

C中strlen的NULL参数

(2018-12-05 14:30:00)
标签:

strlen

分类: C/CPP
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;
}

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有