Reputation: 193
I'm trying to free a struct and am having trouble with it. What I'm programming is kind of an n-ary tree or a virtual file system. I have 2 different structs (one for folders and one for files) and an array for each struct where every element is stored. The structs have a member ID and I've made so I can get a file/folder by using Folders[ID], which will return the struct with that ID. The problem I have is deleting / freeing them. First of all, if it is a folder that will be deleted, it will check recursively for children files and folders and delete these first. For some reason, I just can't get the free() to work, no matter what I try.
My Folder struct:
typedef struct {
FolderID selfID;
FolderID parentID;
/* Other members are not important */
} FolderInfo;
My array:
FolderInfo Folders[MAX_FOLDERS];
How the FolderInfo structs are added to the array (In my new_folder function):
/* ... */
FolderInfo *this = malloc(sizeof (FolderInfo));
/* ... */
ID++;
Folders[ID] = *this;
/* ... */
The delete function:
int32_t delete_folder(FolderID ID) {
if(FolderIsEmpty(ID) == 1) {
return -1; /* Error */
}
/* Check for children and delete them recursively */
/* ... */
free(Folders[ID]);
return 0;
}
Everytime I create a new file/folder, it is added to the file/folder array under the index ID, so Folders[ID] should get the struct with that ID. What am I missing here?
Thanks in advance
Upvotes: 0
Views: 177
Reputation: 25752
Change
FolderInfo Folders[MAX_FOLDERS]
to
FolderInfo* Folders[MAX_FOLDERS]
and
Folders[ID] = *this
to
Folders[ID] = this.
Of course, you can simply refrain from using malloc and free to begin with.
Upvotes: 1