So my problem right now is that for some reason, I designate a pointer as NULL in the first function to be called, but then when I check it later, it’s not NULL anymore.
So I have a few structs, detailed here:
#include <stdio.h>
typedef struct filenode {
struct filenode *next, *prev;
const char *name;
} Filenode;
typedef struct foldernode {
struct foldernode *next, *root, *subdir, *prev;
Filenode *filenodes;
const char *name;
} Folders;
typedef struct Filesystem {
Folders *current;
} Filesystem;
And then I go to my actual file, where I initialize the Filesystem.
This is the initialization function:
void mkfs(Filesystem *files) {
/* Initializes space for the filesystem itself */
files = malloc(sizeof(*files));
if(files == NULL) {
printf("Memory allocation failed!\n");
return;
}
/* Initializes space for the first root node */
files->current = malloc(sizeof(files->current));
if(files->current == NULL) {
printf("Memory allocation failed!\n");
return;
}
files->current->filenodes = NULL;
}
Now, when I go into the next function, mkdir, and I check if files->current->filenodes = NULL, and it is not NULL anymore. I’m extremely confused right now. And yes, the same *files variable is being passed in to every function.
From the comments, you say you can’t change the signature of
mkfs(). I’m going to assume it’s called like this:If that’s the case, you don’t need to create space for the structure (since it’s created on the stack just before your
mkfs()call), so you can remove this line:Removing this line will fix the problem that you can’t see the changes to
filesafter the function has returned. This was causing you trouble since C is always pass by value – the malloc was changing the value of the local copy of thefilespointer, meaning that no further changes were seen outside your function.You will also run into trouble with this line:
Since
files->currentis a pointer to astruct foldernode, the sizeof call only tells you the size of the pointer. You probably meant:or: