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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值