I have a CGI script (C program test.elf
) that gets called by GET method. This means that data is appended to url address that points to the same CGI script. For example:
http://.../cgi/c/test.elf?m=20&n=2000
Here we send data set m=20&n=2000
which is sepparated from the rest of the url with a question mark ?
. Single variables in a data set are also sepparated with &
. So actually we are sending m=20
and n=2000
.
CGI interface automatically stores sent data set m=20&n=2000
in an enviromental variable QUERY_STRING
for the time of the call and I want my CGI script to first print it's (a) value and (b) address.
This is the CGI script:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
// getenv() returns a pointer to character (char*) and we need same type (char*) to store it.
char* data;
// We need an "array of characters" which is actualy the same as "string of characters".
// Because strcpy() can only take pointer to the start of the array we also define another
// pointer and point it to array.
char stored_enviromental_variable[1000];
char* pointer;
pointer = &stored_enviromental_variable[0];
// ASCII HTML header
printf("content-type:text/html; charset=utf-8\n\n");
printf("<h1>Multiplication result</h1>");
// Pointer now points to enviromental variable.
data = getenv("QUERY_STRING");
// We store the value of pointer
strcpy(pointer, data);
// We print some information.
printf("%s: %s<br>", "Value of the \"QUERY_STRING\"", stored_enviromental_variable);
printf("%s: %x<br>", "Address of the \"QUERY_STRING\"", data);
}
This compiles with a warning:
[ziga@localhost ~]$ gcc -Wpedantic -std=c18 -Wall -o test.elf test.c
test.c: In function ‘main’:
test.c:42:15: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 3 has type ‘char *’ [-Wformat=]
printf("%s: %x<br>", "Address of the \"QUERY_STRING\"", data);
~^ ~~~~
%s
So it looks like this source code is causing the problem:
printf("%s: %x<br>", "Address of the \"QUERY_STRING\"", data);
Which is weird to me, because I thought that "pointer always stores location" . So, why does data
store a character? How can I remove the warning?
If I call the CGI script in the browser where I get this:
As the error message states, the %x
format specifier to printf
expects an unsigned int
argument, but you are instead passing in data
whose type is char *
.
To print a pointer value you should use the %p
format specifier. Also, the argument must be casted to void *
:
printf("%s: %p<br>", "Address of the \"QUERY_STRING\"", (void *)data);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.