【发布时间】:2014-11-23 19:38:11
【问题描述】:
我的代码将 char* 行拆分为 char*** cmds,首先按字符 '|'然后是空格、\n 等。示例 I/O:
我:line = "ls -l / | unique | sort"
O:cmds = {{"ls", "-l", "/", NULL}, {unique, NULL}, {sort, NULL}, NULL}
现在,每当到达*cmds = realloc(*cmds, nlines+1); 行超过 1 个字时,它就会产生错误
*** Error in ./a.out': realloc(): invalid next size: 0x000000000114c010 *** 或
a.out: malloc.c:2372: sysmalloc: Assertion (old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1)) & ~((2 *(sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long) old_end & pagemask) == 0)' failed.
任何帮助将不胜感激,我已经花费了数小时的时间......
void parse(char *line, char *** cmds)
{
printf("got line %s\n", line);
size_t nlines = 0;
*cmds = NULL;
while (*line != '\0') {
nlines++;
while (*line == ' ' || *line == '\t' || *line == '\n')
*line++ = '\0';
*cmds = realloc(*cmds, nlines+1);
(*cmds)[nlines-1] = line;
(*cmds)[nlines] = NULL;
while (*line != '\0' && *line != ' ' && *line != '\t' && *line != '\n')
line++;
}
**cmds = '\0';
}
void parsePipe(char *line, char ***cmds)
{
char *cmd = strtok(line, "|");
int linesFound = 0;
while (cmd != NULL)
{
printf("Printing word -> %s\n", cmd);
linesFound++;
parse(cmd, cmds++);
cmd = strtok(NULL, "|");
}
printf("This string contains %d lines separated with |\n",linesFound);
}
void main(void)
{
char line[1024];
char **cmds[64] = {0};
while (1) {
printf("lsh -> ");
gets(line);
printf("\n");
parsePipe(line, cmds);
}
}
【问题讨论】:
-
你在这里只分配 nlines+1 个字节:
*cmds = realloc(*cmds, nlines+1);。您需要为 nlines+1 指针留出空间。 -
另外,
**cmds = '\0。 **cmds 是指向字符的指针,而不是字符。 c2.com/cgi/wiki?ThreeStarProgrammer -
你能告诉我如何解决这个问题吗?我不知道该怎么做,目前也没有时间学习:/
-
使用模式
p = realloc(p, N * sizeof *p)。这将为p指向的任何N项目分配空间。 -
如果你画出所有字符缓冲区和指针在内存中的位置,你可能会发现更容易理解你的代码
标签: c pointers segmentation-fault realloc