C-调试断言失败:_CrtIsValidHeapPointer(block)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C-调试断言失败:_CrtIsValidHeapPointer(block)相关的知识,希望对你有一定的参考价值。

我正在尝试使用VS2019从C中的.csv文件读取,并收到断言错误。我收到的断言错误是_CrtIsValidHeapPointer,我认为它与内存泄漏有关,但我无法意识到是什么触发了它。

任何帮助将不胜感激。

我的结构看起来像这样:

struct movie

    double score;
    char* title;
    int year;
    char* actors;
    char* genre;
;

我的功能是:

void readMoviesFromCSV(movie* movies)

    FILE* inputFile;
    fopen_s(&inputFile, "Movies.csv", "r");

    if (inputFile == NULL)
    
        fclose(inputFile);
        printf("Error opening file.\n");
        exit(1);
    

    char* lineBuffer = (char*)calloc(sizeof(char), 2048);
    char* current = (char*)calloc(sizeof(char), 512);

    fgets(lineBuffer, 2048, inputFile); // Discarding of the header

    for (int i = 0; i < numberOfMovies; i++)
    
        fgets(lineBuffer, 2048, inputFile);

        current = strtok_s(lineBuffer, ",", &lineBuffer);
        (movies + i)->score = atof(current);

        current = strtok_s(lineBuffer, ",", &lineBuffer);
        strcpy_s((movies + i)->title, 512, current);

        current = strtok_s(lineBuffer, ",", &lineBuffer);
        (movies + i)->year = atoi(current);

        current = strtok_s(lineBuffer, ",", &lineBuffer);
        strcpy_s((movies + i)->actors, 512, current);

        current = strtok_s(lineBuffer, "\n", &lineBuffer);
        strcpy_s((movies + i)->genre, 512, current);

        printf("ID: %d\nScore: %.2lf\nTitle: %s\nYear: %d\nActors: %s\nGenre: %s\n\n", i + 1, (movies + i)->score, (movies + i)->title, (movies + i)->year, (movies + i)->actors, (movies + i)->genre);
    

    free(lineBuffer);
    free(current);
    fclose(inputFile);
    return;

我在main中分配了电影数组:

int main()

    movie* movies = (movie*)calloc(sizeof(movie), numberOfMovies);
    for (int i = 0; i < numberOfMovies; i++)
    
        (movies + i)->title = (char*)calloc(sizeof(char), 512);
        (movies + i)->actors = (char*)calloc(sizeof(char), 512);
        (movies + i)->genre = (char*)calloc(sizeof(char), 512);
    

    readMoviesFromCSV(movies);
    // free(movies);
    return 0;

这里可能是什么问题?

答案

至少此行是错误的:

以上是关于C-调试断言失败:_CrtIsValidHeapPointer(block)的主要内容,如果未能解决你的问题,请参考以下文章

调试断言失败:_CrtIsValidHeapPointer(pUserData)

调试断言失败_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

使用 PInvoke 连接 C/C++ DLL 的调试断言失败

调试断言失败表达式:_pFirstBlock == pHead 使用 OpenCV 和 C++ 尝试调用 SurfFeatureDetector

调试断言失败。 BIG_ALLOCATION_ALLIGNMENT

调试断言失败(无符号)(c+1)<= 256(在 VideoCapture::open [Qt Creator] 中)