繁体   English   中英

没有字符串数组崩溃并显示“堆已损坏”

[英]free of array of strings crashes with “A heap has been corrupted”

这个 C 程序读取一个文件,每行一个字。 我想计算文件的唯一词并将其存储在 totalwords 中,该词是通过调用者函数的引用传递的。 该程序创建一个字符串数组来存储已经读取的单词。 还有另一个函数,非常简单,它检查字符串数组中是否已经包含一个单词,称为 isContained(),请参见本文末尾。 一切似乎都正常,我什至检查了这些单词是否始终作为唯一单词存储在数组中。 但是,当释放数组时,会出现错误““堆已损坏”并且程序崩溃。对不起,如果这是一个新手问题,但我仔细检查了一遍,但找不到错误所在。

非常感谢提前

评论后更正(抱歉,我必须清理原始代码的某些部分才能发布示例):@Someprogrammer dude,@ryyker,@kiran biradar,@mlp:我删除了重复的行声明并添加了免费的(行)在最后。 我还为字符串终止保留了空间。 numrecords 已被删除(它是为澄清而删除的原始代码的一部分)。我使用的是 Visual Studio 2019,在调试模式下没有出现错误,只有 4 个警告。 也许我做错了什么。 删除了 sizeof(char)。

谢谢你们。 我再次检查。 这是由于没有附加终止字符的字符串的另一个 malloc。 问题解决了。 非常感谢!

int fileProcessing(char* file_in, int* totalwords) {

    FILE* streamVec;
    char* line = malloc(200);
    int i=0;    
    int numberoflines=1000;
    char** currentList = malloc(numberoflines* sizeof(char*));
    int linelength = 500; //arbitrary value to assure that lines are read completely    

    
    streamVec = fopen(file_in, "r"); 
    if (streamVec == NULL) {
        printf("*** ERROR: Could not open file: %s\n", file_in);
        return 1;
    }

    *totalwords = 0;

    while (fgets(line, linelength, streamVec) != NULL) {      //New line read from the file

                if ( ! isContained(line, currentList, *totalwords)){ //check if the word is already in the list
                        currentList[*totalwords] = malloc(strlen(line) * (sizeof(char)+1));
                        strcpy(currentList[*totalwords], line); 

                        (*totalwords)++;    
                }   
                
    } //End of the read loop

    fclose(streamVec);      

    for (i = 0; i < *totalwords; i++) {
        printf("%i %s\n", i, currentList[i]);       
        free(currentList[i]);       
    }
    free(currentList);
}
int isContained(char* mystring, char** arrayofstring, int arraylength) {

    int i;
    for (i = 0; i < arraylength; i++) {

        if (strcmp(arrayofstring[i], mystring) == 0) {
            return 1;
        }               
    }   
    return 0;
}

您发布的代码可以编译,但在运行时失败。 调试器注释并定位到此位置的第一个故障:

在此处输入图片说明 ...
在此处输入图片说明

内存分配似乎是罪魁祸首。

以下是一些建议,以及可能有助于以下建议的一两个代码片段的链接。

问题陈述

  • 将文件中的单词列表(每行一个单词排列)读入单词数组。
  • 计算数组中不同/唯一单词的列表。

任务清单

  • 从原始文件中获取单词数。
  • 从原始文件中获取最长单词的长度。
  • 创建存储以包含原始文件中的单词列表。
    使用在前两个步骤中收集的信息。)
  • 将原始文件中的单词读入完整的单词数组。
  • 对完整的单词数组进行排序。 (这是可选的。)
  • 使用isContained()函数遍历已排序的完整数组以计算唯一/不同的单词列表。

一些建议的帖子供参考:

从 file 获取单词数 (这可以调整为从文件中获取最长的单词。)
创建存储阵列。
对原始数组进行排序。 using qsort() (同样,可选步骤。)

currentList[*totalwords] = malloc(strlen(line) * (sizeof(char)+1));

这一行是不正确的。 它应该是:

currentList[*totalwords] = malloc((strlen(line) + 1) * sizeof(char));

为了为空终止添加额外的字节。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM