This is a function call (so it is just a part of the whole program). It will generate a segmentation fault. I guess it is caused by “pointer being a local variable”?
int fileExists(const char *fname){
int i = 0;
fseek(fs, sizeof(NODE)*i, SEEK_SET);
NODE* pointer;
fread(pointer, sizeof(NODE), 1, fs);
return 1;
}
Updated:
typedef struct node {
char fname[MAX_NAME];
short fstart;
} NODE;
int findStart (const char *fname){
fs = fopen("Directory", "w+");
NODE* pointer = malloc(sizeof(NODE));
int i;
for(i=0;i<numberNodes;i++){
fseek(fs, sizeof(NODE)*i, SEEK_SET);
fread(pointer, sizeof(NODE), 1, fs);
if(strcmp(pointer->fname, fname)==0)
return pointer->fstart;
}
return 0;
}
So if I want to run through the nodes in the directory file and find the “fstart” of the right node, can I achieve that without the need of free-ing the memory allocated to “pointer”?
The problem is here:
You never allocated any space for
NODE.However, I’m not sure what the purpose is since you’re immediately leaving the function. Don’t forget to later
freethe pointer.Based on the name of the function
fileExists, all you probably need to do is to just try to open the file, check whether it succeeds or fails, then return. All the code here is unnecessary.Something like this will (almost) do what I think you want:
EDIT : Answer to the new question.
To completely avoid the
mallocin the first place you can just putNODEas a local variable on the stack: