debugging 释放结构内部的malloc会使程序崩溃[已关闭]

tct7dpnv  于 2022-12-23  发布在  其他
关注(0)|答案(1)|浏览(113)

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
9小时前关门了。
Improve this question

编辑

好吧,正如你告诉我的,我已经创建了一个最小的可重复的例子,问题仍然存在。

#include <stdlib.h>
#include <stdio.h>

struct Map {
    FILE *ptrToMapFile;
    char *mapChars; // This will be a pointer to a malloc
};

struct Map *initializeMap() {
    struct Map *m = malloc( sizeof( *m ) );
    if ( m == NULL ) {
        printf("Error while creating malloc\n");
        exit(1);
    }

    m->ptrToMapFile = fopen("myFile.txt", "r+");
    if ( m->ptrToMapFile == NULL ) {
        printf("Error while opening file\n");
        exit(1);
    }

    // Saving all the characters of my file in malloc
    // Let's say the file contains exactly 10 chars (counting EOF)
    m->mapChars = malloc( 10 );
    char ch;
    size_t i;
    for ( i = 0; (ch = (char)fgetc(m->ptrToMapFile)) != EOF; i++ ) {
        m->mapChars[i] = ch;
    }
    m->mapChars[i] = '\0';

    return m;
}

int main( void ) {

    for ( size_t i = 0; i < 100; i++ ) {

        struct Map *map = initializeMap();

        printf("%d %s\n\n", i, map->mapChars);

        // Close and free memory
        if ( fclose( map->ptrToMapFile ) == 1 ) {
            printf("Error while closing file\n");
            exit(1);
        }
        free( map->mapChars );
        free( map );

    }

    return 0;
}

myFile.txt只包含这9个字母:第一个月
现在,如果你尝试运行代码,你会发现,经过一些迭代程序将崩溃,但如果你删除代码的free( map->mapChars );行程序将成功运行留下未释放的内存tho.那么我如何才能正确释放mapChars?

xtupzzrd

xtupzzrd1#

是的,正如其他人提到的:当使用malloc进行分配时,您不希望分配指针的大小(malloc(sizeof(type *))),而是分配数据结构的完整大小(malloc(sizeof(type)))。
你确定代码在free()上崩溃了吗?也许可以尝试添加一些语句来打印结构体成员的值。这可能有助于澄清一些问题。
快乐编码!

相关问题