我一直在使用本教程制作 C++ CGI 脚本。但是,当我尝试读取表单 POST 数据时,它没有编译:
char* lpszContentLength = getenv("CONTENT_LENGTH");
char* lpszBuffer;
int nContentLength = atoi(lpszContentLength);
lpszBuffer = malloc(lpszContentLength+1); // allocate a buffer
memset(lpszBuffer, 0, lpszContentLength+1); // zero it out
fread(lpszBuffer,1,lpszContentLength,stdin); // get data
这是编译器的抱怨:
cgi.cpp: In function ‘int main()’:
cgi.cpp:12: error: invalid conversion from ‘char*’ to ‘size_t’
cgi.cpp:12: error: initializing argument 1 of ‘void* malloc(size_t)’
cgi.cpp:12: error: invalid conversion from ‘void*’ to ‘char*’
cgi.cpp:13: error: ‘memset’ was not declared in this scope
cgi.cpp:15: error: invalid conversion from ‘char*’ to ‘size_t’
cgi.cpp:15: error: initializing argument 3 of ‘size_t fread(void*, size_t, size_t, FILE*)’
其中 ln 12 是以“lpszBuffer”开头的那个。
我是 C++ 新手,所以我不确定如何解决这个问题,或者为什么会发生这种情况。也许它只是过时的代码......我很乐意接受其他一些解决方案来从 POST 请求中读取数据。
编辑: 我已经根据你们的修复更新了代码。
char* lpszContentLength = getenv("CONTENT_LENGTH");
char* lpszBuffer;
int nContentLength = atoi(lpszContentLength);
lpszBuffer = (char*)malloc(nContentLength+1); // allocate a buffer
memset(lpszBuffer, 0, nContentLength+1); // zero it out
fread(lpszBuffer,1,nContentLength,stdin); // get data
但是,我仍然从 atoi 收到分段错误:
==23419== Invalid read of size 1
==23419== at 0x498DA8C: ____strtol_l_internal (strtol_l.c:298)
==23419== by 0x498D7EF: strtol (strtol.c:110)
==23419== by 0x498AB60: atoi (atoi.c:28)
==23419== by 0x8048899: main (in .../cgi.cpp.cgi)
==23419== Address 0x0 is not stack'd, malloc'd or (recently) free'd
这里有什么问题?如果 POST 为空白,我假设它与 POST 表单提交有关...