C/C++ strlen參數不能爲null的思考和sizeof的比對

最近C項目中遇到一個異常,查看code後發現是strlen的參數是null引起的,在調用strlen之前判斷參數是否是null解決了問題。現在在具體分析一下strlen。C/C++中的strlen是比較常用的函數,用來計算字符串的長度,計算出的長度不包含結束符’\0’。下面是關於這個函數的介紹。

strlen() function in c
The strlen() function calculates the length of a given string.The strlen() function is defined in string.h header file. It doesn’t count null character ‘\0’.

Syntax:
size_t strlen(const char *str);

Parameter:
str: It represents the string variable whose length we have to find.
Return: This function returns the length of string passed.

上面的介紹很清楚了,我就不多講了,只是感覺奇怪的是爲什麼參數不可以是null,如果是null可以返回0或者一個負數嗎,最好是返回一個負數(-1),這樣的話就能確定現在參數是null。如果返回0,會和str是’\0’而混淆。現在引起NE異常必然是strlen的實現沒有判斷參數是null,而對參數直接進行了操作引起的,動不動引起異常,大家知道在C裏面的這種異常,後果很嚴重,設備可能就直接掛掉了,需要重啓才能恢復。使用strlen的函數的時候一定要小心,要麼能夠確定str不是null,如果不能確定一定在調用strlen之前判斷參數是否是null,尤其是參數是通過其他函數獲取的或者參數已經經過了很長的調用流程才走到了strlen一定要判斷參數是否是null。我比較推薦的是下面的使用方法。

int len = (str == null ? -1 : strlen(str));

另外關於sizeof在這裏也簡單提一下,sizeof不是函數,而是一個運算符,返回的是一個size_t的結果,是編譯時的一元運算符(sizeof的計算髮生在編譯時刻,不是運行時刻),可以用來計算操作數的大小,可以計算變量,也可以計算結構體等類型,和機器相關,不同的機器返回的結果有很大差別。sizeof的作用在字符串和strlen的區別看一下這個例子。

char str[100] = "hello";
int len = strlen(str);//這個返回的值是5;
int size = (int)sizeof(str);這個返回的是100

另外需要額外提醒的是,如果需要分配一塊memory來存儲字符串(malloc或者strncpy),而長度需要通過使用strlen來計算,那分配的memory的大小是srlen(str) + 1,記得一定要爲’\0’留一個位置。下面是三個比較常用的例子。
1

char* output = (char *)malloc(strlen(str) + 1);
if (output != null) {
    memeset(output, 0, strlen(str) + 1);
    memcpy(output. str, strlen(str) + 1);
} else {
    // error handling
}

2

char strout[100] = {0}; // 100 > strlen(str) + 1
strncpy(output, str, strlen(str) + 1);

3

char strout[100] = {0}; // 100 > strlen(str) + 1
strncpy(output, str, strlen(str));
output[strlen(str) + 1] = '\0';

在此總結一下使用strlen使用時候需要注意的地方:
1 參數要判斷是否是null
2 strlen計算的長度不包含結束符’\0’,分配空間或者copy的時候需要考慮結束符,或者copy後在destination str的末尾強制設置爲’\0’。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章