10.请指出下面代码中的错误 char *encode_html(char *html_string) { int i, dst_index; if (!html_string) return NULL; char *dst_buf = (char *)malloc(4 * sizeof (char) * MAX_SIZE); if (MAX_SIZE <= strlen (html_string)) { LOGE ("user string too long, die evil hacker!"); return NULL; } dst_index = 0; for (i =0; i< strlen(html_string);i++) { if ('&'== html_string[i]) { dst_buf[dst_index++] = '&'; dst_buf[dst_index++] = 'a'; dst_buf[dst_index++] = 'm'; dst buf[dst_index++] = 'p'; dst buf[dst_index++] = 'j'; } else if ('<' ==html_string[i]){ /* < Wi11 encoded to &1t; */ } /* other special character */ else dst_buf[dst_index++] = html_string[i]; } return dst_buf; }
时间: 2023-12-03 13:46:11 浏览: 29
代码中存在以下错误:
1. 第14行代码中的变量名错误,应该是“dst_buf”,而不是“dst buf”;
2. 第19行代码中,应该使用 "<" 而不是 "<1t;" 进行 HTML 编码;
3. 第8行代码中的 MAX_SIZE 没有定义,应该将其定义为宏或者参数传入函数中。
正确的代码如下所示:
```c
#define MAX_SIZE 1024
char *encode_html(char *html_string) {
int i, dst_index;
if (!html_string)
return NULL;
char *dst_buf = (char *)malloc(4 * sizeof (char) * MAX_SIZE);
if (MAX_SIZE <= strlen(html_string)) {
LOGE("user string too long, die evil hacker!");
return NULL;
}
dst_index = 0;
for (i = 0; i < strlen(html_string); i++) {
if ('&' == html_string[i]) {
dst_buf[dst_index++] = '&';
dst_buf[dst_index++] = 'a';
dst_buf[dst_index++] = 'm';
dst_buf[dst_index++] = 'p';
dst_buf[dst_index++] = ';';
} else if ('<' == html_string[i]) {
dst_buf[dst_index++] = '&';
dst_buf[dst_index++] = 'l';
dst_buf[dst_index++] = 't';
dst_buf[dst_index++] = ';';
} else if ('>' == html_string[i]) {
dst_buf[dst_index++] = '&';
dst_buf[dst_index++] = 'g';
dst_buf[dst_index++] = 't';
dst_buf[dst_index++] = ';';
} else if ('"' == html_string[i]) {
dst_buf[dst_index++] = '&';
dst_buf[dst_index++] = 'q';
dst_buf[dst_index++] = 'u';
dst_buf[dst_index++] = 'o';
dst_buf[dst_index++] = 't';
dst_buf[dst_index++] = ';';
} else if ('\'' == html_string[i]) {
dst_buf[dst_index++] = '&';
dst_buf[dst_index++] = '#';
dst_buf[dst_index++] = '3';
dst_buf[dst_index++] = '9';
dst_buf[dst_index++] = ';';
} else {
dst_buf[dst_index++] = html_string[i];
}
}
return dst_buf;
}
```