I'm trying to verify that a URL input by a user is in the required format, in this case I am trying to remove the http://
if it is present but I am encountering some very strange problems...
if I feed the function "www.google.com
" or "http://www.google.com
" everything goes as expected! However if I feed it something that is not a valid URL (e.g. potato) it returns gibberish located in memory...
Why this is not necissarily a problem it definitely is NOT expected program behavior, and I have no idea why it's behaving this way...
Enter URL: potato
Error! Could not resolve ip address for host: ╪☻ï*** Process returned 1 ***
Press any key to continue...
Here is the function in question:
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;
}
And here is the portion of my code that returns that particular error message:
if(!(hostip = gethostbyname(hostname)))
{
free(hostname);
free(url);
printf("\nError! Could not resolve ip address for host: %s", hostname);
WSACleanup();
return 0x00;
}
hostname
in the above code is the return value from the for mentioned function.
I'm really not sure what to think.
You are calling a 'free' on hostname and then trying to print it out; of course it will be something unreadable! You should really print it then free it, I guess.