我的代碼將一個char *行分割成一個char *** cmds,首先是字符'|'然後由空格,\ n等樣品I/O:Realoc:分割線時無效的下一個尺寸
I:line = "ls -l/| unique | sort"
○: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指針的空間。 – 2014-11-23 19:43:42
另外,'** cmds ='\ 0'。 ** cmds是指向char的指針,而不是char。 http://c2.com/cgi/wiki?ThreeStarProgrammer – 2014-11-23 19:45:56
請問如何解決這個問題?我不知道如何以及現在沒有時間學習:/ – user3885166 2014-11-23 19:54:07