malloc错误:struct中读取文件的释放对象的校验和不正确

Som*_*oii 0 c malloc

所以我有这个功能:

source_t * source_init(char * argsource)
{
    source_t * temp = (source_t *) malloc(sizeof(source_t *));
    temp->path = realpath(argsource, NULL);
    temp->dir = dirname(temp->path);
    temp->name = basename(temp->path);
    temp->ext = strrchr(temp->name, '.');
    temp->content = read_file(temp->path); // here
    temp->error = error_free();
    return temp;
}
Run Code Online (Sandbox Code Playgroud)

它的调用功能read_file():

char * read_file(char * sourcepath)
{
    char * buffer = NULL;
    long string_size, read_size;
    FILE * file = fopen(sourcepath, "r");
    fseek(file, 0, SEEK_END);
    string_size = ftell(file);
    rewind(file);
    buffer = (char *) malloc(sizeof(char) * (string_size + 1) );
    read_size = fread(buffer, sizeof(char), string_size, file);
    buffer[string_size] = '\0';
    if (string_size != read_size)
    {
        free(buffer);
        buffer = NULL;
    }
    fclose(file);
    return buffer;
}
Run Code Online (Sandbox Code Playgroud)

并且出现了这个错误:malloc: *** error for object 0x7faf08402698: incorrect checksum for freed object - object was probably modified after being freed.所以我当前的解决方案是content在调用source_init()main函数后单独初始化.虽然该解决方案有效,但我希望content在其中进行初始化source_init().此外,似乎我不能直接调用source_init()初始化content因为同样的错误出现所以我必须创建一个缓冲区来调用source_init()和初始化content缓冲区.

Tho*_*thy 5

这可能不是你想要做的:

source_t * temp = (source_t *) malloc(sizeof(source_t *));
Run Code Online (Sandbox Code Playgroud)

这为指向 source_t对象的指针分配空间,也为source_t对象分配空间.

另外,在C中你不应该转换malloc的返回值.这样做可以隐藏错误,并使它们很难找到.

  • 另一个可维护性的原因是使用`source_t*temp = malloc(sizeof(*temp));` (5认同)