I’ve been using this tutorial to make C++ CGI script. However, it’s not compiling when I try to read the form POST data:
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
Here’s the compiler’s complaint:
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*)’
Where ln 12 is the one starting with “lpszBuffer”.
I’m new to C++ so I’m unsure how to fix this, or why this might be happening. Maybe it’s just outdated code… I would happily accept some other solution to read the data from a POST request.
Edit:
I’ve updated the code according to your guys’ fixes.
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
However, I still get a Segmentation fault from 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
What’s the problem here? I’m assuming it has something to do with POST form submission if the POST is blank…
This is a type-cast issue with
C++.lpszBufferis achar*, however,mallocreturns avoid*. So you need to cast it tochar*. Also note that you are trying to use achar*(lpszContentLength) as an integer value which is not true. This must be updated in your other functions as well – you have converted it earlier using theatoifunction; so use that value.So the line should read
Finally, to use
memset, you must#include <string.h>in the beginning of the source file.Also, as good practice (especially if the script runs for any significant amount of time), do not forget to
freeyour memory when you are done with it. That is, anything allocated withmallocshould havefreecalled on it when you are no longer going to use it. So if you uselpszBufferthrough the entire function, at the end of the function simply dofree(lpszBuffer);