游戏技术文章

inet_ntoa内存问题

时间:2017-1-14 12:43:43  作者:棋牌资源网  来源:棋牌资源网  查看:8848  评论:0
内容摘要:最近写的一个程序,大致用到以下代码:  WSADATA wsaData; WSAStartup (MAKEWORD( 2, 2 ),&wsaData); struct addrinfo *aiList=0; sockaddr_in add...
最近写的一个程序,大致用到以下代码:
 
    WSADATA wsaData;

    WSAStartup (MAKEWORD( 2, 2 ),&wsaData);

    struct addrinfo *aiList=0;
    sockaddr_in addr;
    char *ip;

    while (TRUE)
    {
        if (0==getaddrinfo("www.qq.com",0,0,&aiList))
        {
            addr=*(struct sockaddr_in *)aiList->ai_addr;
            ip=inet_ntoa(addr.sin_addr);
        }
        //............................       
    }
 

多次循环之后,发现inet_ntoa破坏栈空间.搜索了一下,inet_ntoa返回的字符串是临时装在一个静态分配的缓冲区里面,下一次调用此函数的时候缓冲区会被重写

http://blog.csdn.net/litingli/article/details/5461535

MSDN:

The string returned by inet_ntoa resides in memory that is allocated by Windows Sockets. The application should not make any assumptions about the way in which the memory is allocated. The string returned is guaranteed to be valid only until the next Windows Sockets function call is made within the same thread. Therefore, the data should be copied before another Windows Sockets call is made.

但是仍然不知道为什么会破坏栈,覆盖了局部变量.

 

解决方案:

 
    WSADATA wsaData;

    WSAStartup (MAKEWORD( 2, 2 ),&wsaData);

    struct addrinfo *aiList=0;
    sockaddr_in addr;
    in_addr in;
    char buffer[32];

    unsigned char *bytes = (unsigned char *) ∈
    __snprintf (buffer, sizeof (buffer), "%d.%d.%d.%d",bytes[0], bytes[1], bytes[2], bytes[3]);  

标签:inet_ntoa内存问题 

欢迎加入VIP,【VIP售价:只要288元永久VIP会员】畅享商业棋牌游戏程序下载,点击开通!

下载说明


☉本站所有源码和资源均由站长亲自测试-绝对保证都可以架设,运营!
☉如源码和资源有损坏或所有链接均不能下载,请告知管理员,

☉本站软件和源码大部分为站长独资,资源购买和收集,放心下载!

☉唯一站长QQ:1004003180  [人格担保-本站注重诚信!]

☉购买建议E-mail:1004003180@qq.com   源码收购 E-mail:1004003180@qq.com    

☉本站文件解压密码  【文章内都自带解压密码,每个密码不同!】


本站提供的所有源码,均来源站长提供,仅学习交流 浙ICP备09009969号

由此产生不良后果和法律责任与本站无关,如果侵犯了您的版权,请来信告知 1004003180@qq.com 将及时更正和删除! 

Copyright © 2008-2024 棋牌资源网,你身边的棋牌资源下载站    All Rights Reserved