I try to parse client HTML GET request and get address of file he wants to send. But when i pass argument to function in path variable is bad output.
Parsers function printf: New file path returned is=/somedir/index.html
Main fuction printf: In main path=random chars
What is wrong?
int parser(char* buffer,char **newPath)
{
int numberOfChars = 0;
int index = 4;//start at 4 char
while(buffer[index] != ' '){
numberOfChars++;
index++;
}
// in numberOfChars is number of path characters from while loop
// this part of code is in if statment but it is irrelevant now
char filePath[numberOfChars];
strncpy(filePath,buffer+4,numberOfChars);
char* fullPath;
fullPath = filePath;
char name[] = "index.html";
strcat(fullPath,name);
(*newPath) = fullPath;
printf("New file path returned is=%s\n",(*newPath));
return 1;
//some more code if file is .sh or .bash or .png ...
.
.
}
main
int main(int argc, char *argv[])
{
//some code
.
.
.
char* path;
//msg is client HTML get request i want parse it and send data
// which he wants
parser(msg,&path);
printf("In main path=%s\n",path);
}
while(buffer[index] != ' '){exits the loop when encountering a space, not when encountering the NUL byte at the end of the string. Then this line:char filePath[numberOfChars]; 1) does not allow room for trailing NUL char. 2) is too small to hold the buffer[5] through the end of the char array. Then this line:strncpy(filePath,buffer+4,numberOfChars);` filled up the flePath[] array (without including a NUL string termination char). Then this line:strcat(fullPath,name);adds yet more characters, 'somewhere' beyond the end of the filePath[] array. ==undefined behaviourstrncpyincorrectly - check its manual to see why