Malloc返回一个指向结构的指针,该结构与另一个结构具有相同的地址

时间:2015-11-02 14:05:46

标签: c malloc

我的项目的目的是创建一个虚拟文件系统。当我尝试为我的根元素创建一个新的子文件夹时,问题仍然存在。它返回一个指向我的根元素的指针,然后“重新分配”那个。

可悲的是,我在C方面缺乏经验,所以我可能忘记添加一些你们可能需要帮助我的细节,所以请不要犹豫,告诉我我忘了添加的内容。

dataTypes.h:

#ifndef VFILESYSTEM_DATATYPES_H
#define VFILESYSTEM_DATATYPES_H

#include "vfilesystem_api.h"

typedef struct Folder Folder;
typedef struct File File;

struct Folder
{
    int32_t folderID;
    int32_t structSize;
    int32_t name_length;
    int32_t file_count;
    int32_t folder_count;
    char *name;
    Folder **parent;
    File **files;
    Folder **folders;
};

struct File
{
    int32_t fileID;
    int32_t structSize;
    int32_t name_length;
    int32_t size;
    char *name;
    Folder **parent;
    uint8_t *data;
};

#endif

create_filesystem_folder:

Folder *create_filesystem_new_folder(char *name, Folder *parent, FolderID folderID)
{
    Folder *folder = NULL;

    if ((folder = malloc(sizeof(Folder))) == NULL)
    {
        printf("ERROR || While creating new folder!\n");

        return NULL;
    }

    if((folder->name = calloc(strlen(name), sizeof(char*))) == NULL)
    {
        printf("ERROR || While creating new folder!\n");
        free(folder);

        return NULL;
    }

    if ((folder->parent = malloc(sizeof(folder->parent))) == NULL)
    {
        printf("ERROR || While creating new folder!\n");

        return NULL;
    }

    folder->folderID = folderID;
    folder->structSize = sizeof(Folder);

    folder->parent[0] = parent;

    folder->file_count = 0;
    folder->folder_count = 0;

    folder->name_length = (int32_t) strlen(name);

    strcpy(folder->name, name);

    folder->files = NULL;
    folder->folders = NULL;

    return folder;
}

0 个答案:

没有答案