日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

libc 无法访问null_C中strlen的NULL参数

發布時間:2023/12/9 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 libc 无法访问null_C中strlen的NULL参数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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;

}

總結

以上是生活随笔為你收集整理的libc 无法访问null_C中strlen的NULL参数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。