我正在尝试将char word[50]
数组复制到char **wordlist
双指针,然后realloc(wordlist, (numwords+1)*sizeof(char*))
将单词列表的大小再增加一char*
来保持下一个word
。
我不断收到*** glibc detected *** ./program: realloc(): invalid next size
错误
我将其声明为wordlist = realloc(wordlist, (numwords+1)*sizeof(char*))
void outFile(char *argv[], char **wordlist)
{
if((inFilePtr = fopen(argv[2], "r")) != NULL)
{
if((outFilePtr = fopen(endOfFile, "w")) != NULL)
{
while((c = fgetc(inFilePtr)) != EOF)
{
if(!(isspace(c)))
{
word[wordIndex] = c;
wordIndex++;
rowLim++;
}
if(isspace(c))
{
wordIndex = 0;
if(rowLim < limit)
{
rowLim++;
strcat(text[rowNum], word);
strcat(text[rowNum], " \0");
wordlist[numwords] = strdup(word);
/*strcat(wordlist[numwords], "\n\0");*/
memset(word, 0, 50);
prev = rowLim;
wordlist = realloc(wordlist, (numwords + 1)*sizeof(char*));
numwords++;
}
else
{
strcat(text[rowNum], "\n\0");
printf("text[%d] = %s",rowNum, text[rowNum]);
fputs(text[rowNum], outFilePtr);
rowNum++;
strcat(text[rowNum], word);
strcat(text[rowNum], " \0");
/*strcat(wordlist[numwords], word);
strcat(wordlist[numwords], "\n\0");
wordlist = realloc(wordlist, (numwords + 1)*sizeof(char*));*/
numwords++;
memset(word, 0, 50);
rowLim = rowLim - prev;
}
wordIndex = 0;
}
}
strcat(text[rowNum], "\n\0");
printf("text[%d] = %s",rowNum, text[rowNum]);
fputs(text[rowNum], outFilePtr);
fclose(outFilePtr);
}
答案 0 :(得分:1)
您在分配空间之前尝试使用空间:
wordlist[numwords] = strdup(word);
wordlist = realloc(wordlist, (numwords + 1)*sizeof(char*));
numwords++;
相反,首先分配空间:
wordlist = realloc(wordlist, (numwords + 1)*sizeof(char*));
wordlist[numwords] = strdup(word);
numwords++;
NB。正如iharob所述,如果您希望能够从内存不足中恢复,那么realloc
的返回值应存储在单独的变量中,直到您确认它不是NULL
为止。
您的所有\0
都是多余的。字符串文字是字符串:例如"\n"
表示已经{ '\n', '\0' }
。
通过在text[rowNum]
中写入太多内容,无法从此代码中判断出是否导致缓冲区溢出。我建议重新设计这段代码,以确保它永远不会溢出。