zoukankan      html  css  js  c++  java
  • 防止atoi函数内存越界

    函数形式为: int atoi(const char *nptr);

        函数说明: 参数nptr字符串,如果第一个非空格字符不存在或者不是数字也不是正负号则返回零,否则开始做类型转换,之后检测到非数字(包括结束符 \0) 字符时停止转换,返回整型数。
    所以在使用时一不小心会造成内存越界,如以下代码:

    #include<stdio.h>

    int main()
    {
    char a='7';
    char b='2';

    printf("a=%d,b=%d\n",atoi(&a),atoi(&b));
    return 0;
    }

    输出结果:

    a=7,b=27

    修改代码如下:

    #include<stdio.h>

    int main()
    {
    char a='7';
    char b='2';

    printf("a=%d,b=%d\n",atoi(&a),atoi(&b));
    printf("a=%p,b=%p\n",&a,&b);
    return 0;
    }

    输出结果:

    a=7,b=27

    a=0x7fff85cd714f,b=0x7fff85cd714e

    由此可见,atoi()在转换b时第一个去的自符2,之后去的自符7,所以atoi(&b)输出结果27,所以在实际使用中如果不能确定内存数据排列情况尽量不要用atoi(),最好自己写个转换函数。

    也可定义一个buf,用类似snprintf()函数将字符放到buf中再调用atoi()函数。

  • 相关阅读:
    Hashmap实现原理
    策略模式
    Google Drive ubuntu
    numix Docky
    Google Drive 和 Dropbox 同步同一个文件夹目录
    sublime text 2
    matlab cell
    liteide
    taglist and nerdtree
    codeblocks
  • 原文地址:https://www.cnblogs.com/wangliangblog/p/5121955.html
Copyright © 2011-2022 走看看