奇怪的字符串行为

Kei*_*ler 0 c sockets resolve

我正在尝试验证用户输入的URL是否为所需格式,在这种情况下,我试图删除http://它是否存在但我遇到了一些非常奇怪的问题...

如果我提供功能" www.google.com"或" http://www.google.com"一切按预期进行!但是,如果我给它提供的东西不是有效的URL(例如马铃薯),它会返回位于内存中的乱码...

为什么这不是一个问题,它肯定不是预期的程序行为,我不知道它为什么会这样做...

Enter URL: potato

Error! Could not resolve ip address for host: ??ï*** Process returned 1 ***
Press any key to continue...
Run Code Online (Sandbox Code Playgroud)

这是有问题的功能:

char *bldurl(const char *url)
{
    char *nurl;
    int ch = 0, i = 0;

    if(chksbstr(url, "http://") < 0)
    {
        if(!(nurl = malloc(strln(url) + 8)))
        {
            printf("\nError! Memory allocation failed while appending URL!");
            return 0x00;
        }
        nurl[ch] = 'h';
        nurl[++ch] = 't';
        nurl[++ch] = 't';
        nurl[++ch] = 'p';
        nurl[++ch] = ':';
        nurl[++ch] = '/';
        nurl[++ch] = '/';
        for(++ch; i <= strln(url); ch++, i++) nurl[ch] = url[i];
        nurl[--ch] = 0x00; 
    }
    else
    {
        if(!(nurl = malloc(strln(url) + 1)))
        {
            printf("\nError! Memory allocation failed while appending URL!");
            return 0x00;
        }
        for(i = 0; i <= strln(url); i++) nurl[i] = url[i];
        nurl[i + 1] = 0x00;
    }
    return nurl;
}
Run Code Online (Sandbox Code Playgroud)

这是我的代码中返回该特定错误消息的部分:

    if(!(hostip = gethostbyname(hostname)))
    {
        free(hostname);
        free(url);
        printf("\nError! Could not resolve ip address for host: %s", hostname);
        WSACleanup();
        return 0x00;
    }
Run Code Online (Sandbox Code Playgroud)

hostname 在上面的代码中是来自上述函数的返回值.

我真的不确定该怎么想.

Nas*_*san 5

您在主机名上调用"免费",然后尝试将其打印出来; 当然这将是一件难以理解的事情!你应该打印它,然后释放它,我想.