首页 > Web开发 > 详细

inet_ntoa内存问题

时间:2014-07-28 15:20:03      阅读:344      评论:0      收藏:0      [点我收藏+]

最近写的一个程序,大致用到以下代码:

bubuko.com,布布扣
    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);
        }
        //............................       
    }
bubuko.com,布布扣

多次循环之后,发现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.

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

 

解决方案:

bubuko.com,布布扣
    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]);        
bubuko.com,布布扣

inet_ntoa内存问题,布布扣,bubuko.com

inet_ntoa内存问题

原文:http://www.cnblogs.com/rainbowzc/p/3872887.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!