C档案:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
FILE *ptr;
char m[200];
char *data = malloc(200);
data=getenv("QUERY_STRING");
sscanf(data,"%s", m);
printf("%s", m);
ptr=fopen("c:/test.txt", "w");
fprintf(ptr, "%s", m);
fclose(ptr);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
// gcc -g print.c -o print.exe
HTML文件:
<html>
<body>
<h2>CGI Server</h2>
<p>
<form action="http://localhost/cgi-bin/print.exe">
<div><label>value: <input name="m" size="10"></label></div>
<div><input type="submit" value="Run"></div>
</form>
</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
如果输入到网页表单是c:/data.txt,则结果为:c%3A%2Fdata.txt
发生了什么?为什么输出中的/和:损坏了?似乎问题出在QUERY_STRING上,因为getenv("PATH")不会出现这个问题.
char *data = malloc(200);
data=getenv("QUERY_STRING");
Run Code Online (Sandbox Code Playgroud)
内存泄漏在这里.您正在分配200个字节,您永远不会使用或无法使用free().(或者不是,因为malloc()可能会失败并返回NULL.)
char m[200];
sscanf(data,"%s", m);
Run Code Online (Sandbox Code Playgroud)
这是strcpy()/ 的原始替代品strncpy().如果查询字符串长度超过200个字符,则导致缓冲区溢出.一旦找到空格也会终止,但这不是问题,因为它们已被转向+或%20在URL编码期间.
ptr=fopen("c:/test.txt", "w");
fprintf(ptr, "%s", m);
Run Code Online (Sandbox Code Playgroud)
fopen()可能会失败,导致返回值为NULL.
我建议你查看指针和内存分配,查找除printf/scanf之外的一些字符串操作函数,并养成检查错误的习惯,即防御性编码.即使是小的,示例质量的代码.