aoti使用注意,越界問題以及Segmentation fault問題

int atoi( const char *str );

官方解釋:

Interprets an integer value in a byte string pointed to by str.

Discards any whitespace characters until the first non-whitespace character is found, then takes as many characters as possible to form a valid integer number representation and converts them to an integer value. The valid integer value consists of the following parts:

  • (optional) plus or minus sign
  • numeric digits

Parameters

str - pointer to the null-terminated byte string to be interpreted

Return value

Integer value corresponding to the contents of str on success. If the converted value falls out of range of corresponding return type, the return value is undefined. If no conversion can be performed, 0 is returned.

先說明下當atoi的輸入爲nullptr,會Segmentation fault

下面舉幾個例子

#include <iostream>
#include <cstdlib>
#include <string>

int main()
{
    const char *str1 = "42";
    const char *str2 = "3.14159";
    const char *str3 = "31337 with words";
    const char *str4 = "words and 2";
    std::string str5 = "-122";

    int num1 = std::atoi(str1);
    int num2 = std::atoi(str2);
    int num3 = std::atoi(str3);
    int num4 = std::atoi(str4);
    int num5 = std::atoi(str5.c_str());

    std::cout << "std::atoi(\"" << str1 << "\") is " << num1 << '\n';
    std::cout << "std::atoi(\"" << str2 << "\") is " << num2 << '\n';
    std::cout << "std::atoi(\"" << str3 << "\") is " << num3 << '\n';
    std::cout << "std::atoi(\"" << str4 << "\") is " << num4 << '\n';
    std::cout << "std::atoi(\"" << str5 << "\") is " << num5 << '\n';
}
// output
std::atoi("42") is 42
std::atoi("3.14159") is 3
std::atoi("31337 with words") is 31337
std::atoi("words and 2") is 0
std::atoi("-122") is -122

上述例子將所有字符串進行轉換,若只轉換字符串中的一部分,可能就需要考慮越界的情況,當然下面的例子是通過(point+index)的方式進行輸入的,若直接通過c_str()可無視。

#include <iostream>
#include <string>

using namespace std;

int main() {
    string str = "12345678";
    char *ch = const_cast<char *>(str.c_str());
    int num1 = atoi(ch + 2);
    int num2 = atoi(ch + 5);
    int num3 = atoi(ch + 25); // maybe Segmentation fault

    cout << "num1 : " << num1 << endl;
    cout << "num2 : " << num2 << endl;
    cout << "num3 : " << num3 << endl;

    cout << "ch1 : " << ch + 2 << endl;
    cout << "ch2 : " << ch + 5 << endl;
    cout << "ch3 : " << ch + 25 << endl;
}
// output
num1 : 345678
num2 : 678
num3 : 0
ch1 : 345678
ch2 : 678
ch3 : @

在11行可能會出現Segmentation fault的問題,小概率事件,在19行的打印信息中可以看出,輸出的信息是隨的,有可能就執行了nullptr,就出現了Segmentation fault

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