此代码应该从 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 */
根据 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)
在 stackoverflow 上搜索类似的问题,一些人谈到添加空终止符,而另一些人则提到使用memcpy
而不是strcpy
; 无论如何,我正在添加一个 null 并且我尝试使用memcpy
但没有任何改进,valgrind 一直在抱怨。
我在这里到底做错了什么?我该如何解决?