Clueless Intern Clueless Intern - 1 year ago 100
HTML Question

Trying to copy char pointer to "QUERY_STRING" to a char[] variable, getting wrong result

I am working with FastCgi, trying to generate a dynamic html webpage.

I am able to get the QUERY_STRING easily enough, but I am having trouble trying to copy it into a char array.

If there is even a shorter way of just getting the value from QUERY_STRING, please advise because I am a little over my head.

char *queryString = getenv(ENV_VARS[7]);
char newDeviceName[64];

strncpy( newDeviceName, *queryString, sizeof(*queryString) -1);
printf("------- %c ------------", newDeviceName);

This compiles with only warnings, but once i try to load the webpage, the characters are some weird Chinese looking characters. -> �ፙ�

Thank you in advance.

EDIT: More of my code

const char *ENV_VARS[] = {

int main(void)
char deviceName[]=ADAPTERNAME;
time_t t;
/* Intializes random number generator */
srand((unsigned) time(&t));

while (FCGI_Accept() >= 0) {

printf("Content-type: text/html \r\n\r\n");
printf("<script src=\"/js/scripts.js\"></script>");


printf("<p> hi </p>");
printf("<p> hi </p>");
char *queryString = getenv(ENV_VARS[7]);
char newDeviceName[64];
if (queryString == NULL)
printf("<p> +++++ERROR++++++ </p>");
else {
strcpy( newDeviceName, queryString);
newDeviceName[sizeof(newDeviceName) - 1] = 0;
printf("<p> ------- %s ------------ </p> ", newDeviceName);

SOLVED: Amateur mistake, for some reason none of my new edits went into effect until after i restart my lighttpd server.

Answer Source

Your program has undefined behavior. Read those warnings issued by the compiler. They're important.

Don't dereference the pointer when you're passing the string to strncpy(). When you do that, you're now passing a single char. That's converted to a pointer when it's given to strncpy() (which is where you probably get your warning, i.e. passing a char to a function that expects a char*).

You also can't get the size of an array that has decayed to a pointer using sizeof. You're just getting the size of the pointer (which is probably either 8 or 4 bytes depending on your system). Since you don't know the length of the string anyway, it might even be better to just use strcpy() instead of strncpy().

Here's what your code probably should look like:

char *queryString = getenv(ENV_VARS[7]);
char newDeviceName[64];

strcpy( newDeviceName, queryString);
printf("------- %s ------------", newDeviceName); /* use %s to print strings */
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download