zoukankan      html  css  js  c++  java
  • inet_ntoa内存问题

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

        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]);        
  • 相关阅读:
    Android px,dp,pt,sp的差别
    C 八皇后
    线性表
    android 推断手机是否支持前置摄像头
    C/C++易错难点笔记01
    Java日志记录的5条规则
    hdoj-1312-Red and Black
    oracle 11g sql developer安装后无法使用
    显示指定时间的秒数
    云端自动化测试方案
  • 原文地址:https://www.cnblogs.com/nethirte/p/2975108.html
Copyright © 2011-2022 走看看