【发布时间】:2015-12-09 14:18:48
【问题描述】:
我尝试解析客户端 HTML GET 请求并获取他想要发送的文件地址。但是当我将参数传递给路径变量中的函数时输出错误。
解析器函数 printf:New file path returned is=/somedir/index.html
主函数printf:In main path=random chars
怎么了?
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 ...
.
.
}
主要
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] != ' '){在遇到空格时退出循环,而不是在遇到字符串末尾的 NUL 字节时。然后这一行: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);` 填充了 flePath[] 数组(不包括 NUL 字符串终止字符)。然后这一行:strcat(fullPath,name);在 filePath[] 数组末尾的“某处”添加了更多字符。 ==未定义的行为 -
您错误地使用了
strncpy- 查看其手册了解原因