【发布时间】:2016-03-02 19:34:36
【问题描述】:
几个小时以来,我一直在处理烦人的内存损坏错误。我已经检查了这里的每个相关线程,但我无法修复它。
首先,我正在用 C 语言编写一个简单的终端。我正在解析管道 (|) 和重定向 (>、
这是队列的数据结构;
struct command_node {
int index;
char *next_symbol;
struct command_node *nextCommand;
int count;
char **args;
};
当我在 **args 指针中存储小字符串时,一切正常。但是,当其中一个参数很长时,我得到 malloc(): memory corruption 错误。例如,以下第 1 个命令可以正常工作,第 2 个命令会导致错误
1st: ls -laF some_folder | wc -l
2nd: ls -laF /home/enesanbar/Application | wc -l
我运行调试器,它显示对队列中新节点的 malloc() 调用导致错误。
newPtr = malloc( sizeof(CommandNode) );
我正在仔细分配字符串数组并在完成后释放它们,如下所示:
char **temp = NULL;
temp = malloc(sizeof(char*) * number_of_args);
/* loop through the argument array */
for (i = 0; i < number_of_args; i++) {
/* ignore the remaining commands after ampersand */
if (strcmp(args[i], "&") == 0) return;
/* split commands by the redirection or pipe symbol */
if (!isSymbol(args[i])) {
temp[count] = malloc(sizeof(strlen(args[i])) + 1);
strcpy(temp[count], args[i]);
count++;
/* if it is the last argument, assign NULL to the symbol in the data structure */
if (i + 1 == number_of_args) {
insertIntoCommands(&headCommand, &tailCommand, temp, NULL, count);
for (j = 0; j < count; j++) free(temp[j]);
count = 0; // reset the counter
}
}
else {
insertIntoCommands(&headCommand, &tailCommand, temp, args[i], count);
for (j = 0; j < count; j++) free(temp[j]);
count = 0; // reset the counter
}
}
我一定错过了什么,或者我不知道 **args 字段和新节点的分配,尽管这不是我以前没有做过的事情。
【问题讨论】:
-
temp[count]count? -
它是为了跟踪下一个参数的放置位置,并且在打印用于调试的内容时,我也会将其存储起来以方便使用。
-
sizeof(strlen(...可能不是您想要的。删除大小 -
谢谢,这解决了这个问题,但是在 sizeof 周围包裹一个数字怎么会导致节点分配错误呢?出于好奇,我只是想了解一下。
-
您尝试在
strlen函数中获取指针的大小,而不是通过函数提供的长度。
标签: c pointers memory malloc corruption