【发布时间】:2014-09-18 17:33:27
【问题描述】:
我在下面写了C代码来获取url参数的值。
char *param(char *attribute_name) {
char *query_str = getenv("QUERY_STRING");
urlDecode(query_str);
printf("qstr = %s<br/>", query_str);
int i;
char *param_value;
char *temp = malloc(strlen(attribute_name) + 3);
char *x;
strcpy(temp, "?");
strcat(temp, attribute_name);
strcat(temp, "=");
x = strstr(query_str, temp);
attribute_name = strdup(attribute_name);
if (x == NULL) {
free(temp);
temp = malloc(strlen(attribute_name) + 3);
strcpy(temp, "&");
strcat(temp, attribute_name);
strcat(temp, "=");
x = strstr(query_str, temp);
}
if (x != NULL) {
param_value = malloc(strlen(x) - strlen(temp) + 1);
int s = strlen(x) - strlen(temp);
int t = strlen(x) - s;
strncpy(param_value, &x[t], 1);
for (i = strlen(temp) + 1; i <= strlen(x); i++) {
if (x[i] != '&') {
strncat(param_value, &x[i], 1);
} else {
break;
}
}
}
free(temp);
return param_value;
}
int urlDecode(char *str) {
unsigned int i;
char tmp[BUFSIZ];
char *ptr = tmp;
memset(tmp, 0, sizeof(tmp));
for (i=0; i < strlen(str); i++) {
if (str[i] != '%') {
*ptr++ = str[i];
continue;
}
if (!isdigit(str[i+1]) || !isdigit(str[i+2])) {
*ptr++ = str[i];
continue;
}
*ptr++ = ((str[i+1] - '0') << 4) | (str[i+2] - '0');
i += 2;
}
*ptr = '\0';
strcpy(str, tmp);
return 0;
}
下面是我的 main() 函数:
int main() {
printf("Content-type: text/html\n\r\n\r");
printf("<!Doctype html>");
printf("<html>");
printf("<meta charset=\"UTF-8\"><meta http-equiv=\"Content-type\" content=\"text/html; charset=UTF-8\">");
printf("<body>");
char attr[] = "u";
char *value = param(attr);
puts(value);
//free(value);
printf("</body></html>");
return 0;
}
以下是我在点击 url 后在浏览器上收到的输出:http://example.com/cgi-bin/cgi_param?u=1212&sa=232%203&sdd=jdwjdjw
qstr = u=1212&sa=232 3&sdd=jdwjdjw
�l12�
请纠正我在哪里做错了? 谢谢
【问题讨论】:
-
先缩小错误点,并指定这是C还是C++(看起来是C)
-
三件事:首先
strncpy可能并不总是添加字符串终止符,在你的情况下它不会。其次,为什么使用例如strncpy只是为了复制 一个 字符?第三,使用调试器逐行遍历代码,看看会发生什么。 -
您是否已经调试过您的代码?我们不是人类调试器(还......但我们仍在努力提高我们的运行时技能)