【发布时间】:2019-12-13 01:58:06
【问题描述】:
我现在正在学习 C 编程课程,并且正在制作一个类似于 bash 的 shell。现在,我正在努力实现管道。出于这个原因,我需要 strndup 管道命令在解析时不要修改原始管道命令。最后,我尝试freemalloc'd 指针,但随后我的程序无法正常工作。有人可以告诉我我做错了什么吗?下面是我的解析器的 while 循环代码:
while (pipeSeparatedCommand != NULL) {
char *duplicateCmdForPiping = strndup(pipeSeparatedCommand, strlen(pipeSeparatedCommand)); // duplicates command
pipeSeparatedCommand = strtok(NULL, "|"); // starts at the NULL Character that was tokenized
char *token = strtok(duplicateCmdForPiping, " "); // finds the first space in the command, tokenizes the arguments by this space
int index = 0; // counts the number of commands and arguments
while (token != NULL) {
if ((input != NULL) || (output != NULL)) { // advances to the next argument if input or output is found (does not include them in args)
token = strtok(NULL, " ");
continue;
}
commandArgsCount[index]++;
commandArray[numberOfPipes][index] = token; // sets the argument index equal to the address of token (containing the token)
token = strtok(NULL, " "); // token will search for the next delimiter from the last delimiter end spot
index++;
}
commandArray[numberOfPipes + 1][index] = NULL; // prevents the args array from collecting garbage in memory.
if (pipeSeparatedCommand != NULL) // catches the zero case
numberOfPipes++; // this begins at zero, increments if more pipes need to be added
free(duplicateCmdForPiping);
duplicateCmdForPiping = NULL;
}
【问题讨论】:
-
当您确定它们不再在程序中的其他任何地方被引用时,您就可以释放它们,并且它们不是必需的。何时何地适合此标准由您在编写代码时决定。
-
commandArray[numberOfPipes][index] = token;- 一旦调用free(duplicateCmdForPiping);,就会留下一个悬空指针。这与malloc/free的关系与strtok的工作方式同样重要。 (提示:它不复制 任何东西;而是在原始字符串中设置终止符(strndup的结果)并返回相同的指针)。 -
@Frontear:这不是一个正确的标准。只要不使用这些引用,就可以释放仍有引用的内存。例如,当释放链表上的多个项目时,我们可能会释放一个项目,即使前一个项目仍然指向它,因为前一个项目也将被暂时释放或其中的指针会改变。