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]); 
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值