-1

I'm curently developping a web application in C on a Debian (don't ask me why). I made a method to get the data from a form using POST :

const char* getParam(char* postResult, char* param)
{
char stock[30];
char* pointer = strstr(postResult, param);
while(*pointer != 61)
    pointer++;

int i = 0;
++pointer;
while(*pointer != 38)
{
    stock[i] = *pointer;
    i++;
    *pointer++;
}
stock[i] = 0;
const char *result;
if(stock[0] == 0) {
    result = "";
}else{
    result = stock;
}
return result;
}

when calling this method I store the data in a variable declared by

char fname[40]; 

like this

strcpy(fname,getParam(ptr, "firstn"));

Then when trying to display the data it shows weird characters.

2 Answers2

0

You are returning a pointer to a local variable (stock) that is not available anymore if the function is finished.

Make stock static to make it stay or make it an dynamically allocated memory or pass fname into the function and store it there.

In any case you need to make sure that the memory you store the content is there as long you use it.

chris01
  • 10,921
  • 9
  • 54
  • 93
0

Instead returning a pointer to a local var inside getParam(), you can pass a pointer to a buffer.

const char* getParam(char *stock, char* postResult, char* param)
{
  // char stock[20] you do not need that anymore
  char* pointer = strstr(postResult, param);
  while(*pointer != 61)
    pointer++;

  // int i = 0;
  ++pointer;

  // Move that up
  if( pointer==0 )
  {
    *stock=0;
    return;
  }

  while(*pointer != 38)
  {
    *stock = *pointer;
    stock++;
    *pointer++;
  }
  stock = 0;

}

In this case you do not need to use strcpy(), too:

char fname[40]; 
getParam(fname, ptr, "firstn"));

Typed in browser.

However, you should check for too long args and for strings without 38. In your current version there is an attack vector for buffer overflows.

Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50