更改函数中的指针字符值

标签 c pointers char

我尝试解析客户端 HTML GET 请求并获取他想要发送的文件的地址。但是当我将参数传递给路径变量中的函数时,输出是错误的。 解析器函数 printf: 返回的新文件路径 is=/somedir/index.html 主要功能 printf: 在主路径=随机字符

出了什么问题?

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);
}

最佳答案

char filePath[numberOfChars];    
char* fullPath;
fullPath = filePath; 
....
(*newPath) = fullPath;

filePath 具有自动存储期限,您将在其生命周期结束后访问它。这是undefined behaviour .

相反,您可以使用 malloc()strcpy() 将字符串复制到 *newPath

替换

(*newPath) = fullPath;

与:

*newPath = malloc(strlen(fullPath) + 1);
 if (*newPath == NULL) {
    /* handle error */
 }
strcpy(*newPath, fullPath);

并调用free()main() 中取消分配它。


正如注释中所指出的,您需要为 '\0' 终止符分配一个额外的字节。您可以通过分配额外的字节来处理这个问题:

char filePath[numberOfChars + 1];    
strncpy(filePath,buffer+4,numberOfChars);
filePath[numberOfChars] = '\0';

strncpy() 自动用 NUL 字节填充内存的其余部分。在本例中,仅是最后一个字节。一般来说,您不想使用 strncpy(),因为没有必要用 NUL 字节填充缓冲区的其余部分。

关于更改函数中的指针字符值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34181068/

相关文章:

c - 找出 AF_UNIX + SOCK_SEQPACKET 最大消息大小

c++ - 在记录错误时取消引用 ptr 是错误的设计吗?

c - 将 char* 传递给 pthread 崩溃

无法访问函数 C 中的 2 DIM 数组

c - 了解 ctime 代码

c - 通过读取字符串检测数据类型

c++ - 使用算术符号来遍历字符串

c - 动态数据结构

c - scanf char* word in struct 仅显示最后输入

在 C 中创建从 getline() 读取的单词的 char**