I have written the following code in order to:
- Find begin and end of FTP user and password from a given URL (
ftp://[user[:password]@]host[:port]/url-path
) - Allocate memory to hold this string
- Copy the sub-string into the allocated memory
Here is the code for your review:
static char * swd_parseUsrPass(void)
{
char *usr_pass = NULL;
char *url_str = NULL;
char *beginIndx = NULL;
char *endIndx = NULL;
int str_len = 0;
url_str = getURLaddr();
/* Find begin and end indexs */
beginIndx = url_str + strlen(FTP_PREFIX);
endIndx = strchr(beginIndx, '@');
if ((endIndx == NULL) || endIndx <= beginIndx) {
printf("Could not locate user and password in URL\n");
return NULL;
}
str_len = endIndx - beginIndx;
/* Allocate maximum possible string */
usr_pass = malloc((sizeof(char) * str_len) + 1);
if (usr_pass == NULL) {
printf("Failed to allocated memory!\n");
return NULL;
}
/* Copy user and password to new string */
strncpy(usr_pass, beginIndx, str_len);
*(endIndx + 1) = '0円';
return usr_pass;
}
2 Answers 2
A 0-ary function (
swd_parseUsrPass
) calling another 0-ary function (swd_getURLaddr
) hints that there are global variables lurking around. Using globals is not recommended; if they are unavoidable, at least limit their visibility. Considerchar swd_parseUsrPass(char * url_addr)
, and let the caller provide the argument.sizeof(char)
is guaranteed to be 1.*(endIndx + 1) = '0円'
modifies the source string, whileusr_pass
remains not terminated. I presume you meantusr_pass[str_len] = '0円';
-
\$\begingroup\$ Thank you @vnp. I'm actually not using global variables, but I do use static variables (defined only in this C file content) - do you see any problem with that? \$\endgroup\$dear_tzvi– dear_tzvi2016年10月09日 17:54:56 +00:00Commented Oct 9, 2016 at 17:54
I agree with all points made by vnp, except I'd suggest swd_parseUsrPass(const char *url_addr)
as the prototype, and I'd add:
- all your pointers except
usr_pass
should beconst char *
as you do not intend to modify the string they point to. This would have help you noticing the*(endIndx + 1) = '0円'
issue pointed out by vnp. - the test
endIndx <= beginIndx
seems redundant to me - I'm not a big fan of
Indx
in the name: these are pointers, indexes would be integers (not a big fan of mixing underscores and camelCase either, but that's more an issue of taste)
@
character can appear in theurl-path
\$\endgroup\$url-path
may not be there so you have to check for all the common mistakes.?
,&
,#
,:
\$\endgroup\$