valcind错误与strcpy

Fin*_*fin 4 c linux memory string valgrind

此代码应该从userInput以null结尾的字符串中提取路径

  /* begin createPath */
    static inline char* createPath(char * userInput)
    {/* This function retuns the path from the userInput */
            int pathStringLength = 0;
            char *buf = userInput;
            while(*(buf++) != ' ')
                    pathStringLength++;
            char *path = malloc(pathStringLength+1);
            strncpy(path, userInput, pathStringLength);
    //      memcpy(path, userInput, pathStringLength);
            path[pathStringLength+1] = '\0';        
            return path;
    }
    /* end createPath */
Run Code Online (Sandbox Code Playgroud)

根据valgrind,此代码有错误:

> ==2919== Conditional jump or move depends on uninitialised value(s)
> ==2919==    at 0x400A87: createPath (in /home/aral/learn/myShell/myShell)
> ==2919==    by 0x400A4C: parseInput (in /home/aral/learn/myShell/myShell)
> ==2919==    by 0x4009C3: main (in /home/aral/learn/myShell/myShell)
> ==2919== 
> ==2919== Invalid write of size 1
> ==2919==    at 0x400AC3: createPath (in /home/aral/learn/myShell/myShell)
> ==2919==    by 0x400A4C: parseInput (in /home/aral/learn/myShell/myShell)
> ==2919==    by 0x4009C3: main (in /home/aral/learn/myShell/myShell)
Run Code Online (Sandbox Code Playgroud)

在stackoverflow上搜索类似的问题,有些人谈到添加null-terminator而其他人提到使用memcpy而不是strcpy; 无论如何我添加了一个null,我尝试使用memcpy但没有任何改进,valgrind一直在抱怨.

这到底我做错了什么?我该如何解决?

Dav*_*nan 6

path[pathStringLength+1] = '\0';
Run Code Online (Sandbox Code Playgroud)

是错的.那是最后一个字节.你的意思是:

path[pathStringLength] = '\0';
Run Code Online (Sandbox Code Playgroud)

如果输入字符串没有空格,您还将有一个缓冲区溢出.检查循环中的null终止符,并在遇到循环时终止.我写的是这样的:

while (*buf != ' ' && *buf != '\0')
{
    pathStringLength++;
    buff++;
}
Run Code Online (Sandbox Code Playgroud)

对于它的价值,我认为memcpy这可能是一个更好的选择.一旦你确切地知道需要复制多少文本,你也可以将它搞砸.不需要查找空终止符的字符串函数.修复代码后,您已经检查过它们.

你应该检查的返回值malloc.