当我运行程序时,我的控制台输出显示如下: malloc():内存损坏(快速),后面跟着内存中的地址。我把它缩小到几个函数,但我觉得我释放了我正确分配的所有内存。
以下函数采用表示文件名的字符串。
void readAndProcessFile(char* filename){
FILE *fileptr;
char* word = malloc(32*sizeof(char));
fileptr = fopen(filename, "r");
while(fscanf(fileptr,"%s",word) != EOF){
processWord(word);
}
fclose(fileptr);
free(word);
}
此函数接受一个单词,删除所有非字母字符并将所有字母更改为大写。
void processWord(char* text){
char* processedWord;
processedWord = trimAndCaps(text);
if(processedWord != NULL && processedWord[0] != '\0'){
addWord(processedWord);
}
free(processedWord);
}
这是修剪和上限功能
char* trimAndCaps(char* text)
{
int i = 0;
int j = 0;
char currentChar;
char* rv = malloc(sizeof(text));
while ((currentChar = text[i++]) != '\0')
{
if (isalpha(currentChar))
{
rv[j++] = toupper(currentChar);
}
}
rv[j] = '\0';
return rv;
}
这里有一个好的衡量标准是addWord函数
void addWord(char* word)
{
// check if word is already in list
struct worddata* currentWord = findWord(word);
// word is in list
if(currentWord != NULL)
{
incrementCount(currentWord);
}
// word is not in list
else
{
currentWord = malloc(sizeof(struct worddata));
currentWord->count = 1;
strcpy(currentWord->word, word);
ll_add(wordList, currentWord, sizeof(struct worddata));
free(currentWord);
}
}
正如您所看到的,我手动分配内存的所有实例,之后都是免费的。此程序在单词数量较少时有效,但对较大单词则无效。我的思维过程让我相信存在某种泄漏,但是当我有足够的话来说明我可以运行它时,我运行以下代码:
// The following code will print out the final dynamic memory used
struct mallinfo veryend = mallinfo();
fprintf(stderr, "Final Dynamic Memory used : %d\n", veryend.uordblks);
每次使用内存时都会显示0。还有什么可以导致这个?任何方向或修正都非常感谢。
答案 0 :(得分:3)
以下行不符合您的要求:
char* rv = malloc(sizeof(text));
它只分配4
或8
个字节或内存,具体取决于平台上指针的大小。
你需要:
char* rv = malloc(strlen(text) + 1);