Inet_ntoa Memory Issues

Source: Internet
Author: User

Recently wrote a program that roughly uses the following code:

Wsadata Wsadata; WSAStartup (Makeword (2,2),&Wsadata);struct addrinfo *ailist=0 char *IP; whileif (0==getaddrinfo ( "www.qq.com 0,0,&ailist) {addr=* (struct sockaddr_in *) ailist->ai_ Addr Ip=inet_ntoa (ADDR.SIN_ADDR);} //    

After many cycles, it is found that Inet_ntoa destroys the stack space. After searching, the string returned by Inet_ntoa is temporarily loaded in a statically allocated buffer, and the buffer is rewritten the next time this function is called.

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

Msdn:

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

But still don't know why the stack is broken, overwriting the local variables.

Solution:

Wsadata Wsadata; WSAStartup (Makeword (2,2),&Wsadata);struct addrinfo *ailist=0 in char buffer[32char *bytes = (unsigned char *) &insizeof (buffer),  "%d.%d.%d.%d" ,bytes [0], Bytes[1], Bytes[2 ], Bytes[3]);  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.