c - Getting Segmentation fault while searching in a file -


i'm writing code simple database holds information of type "info".

here's code:

#include <string.h> #include <stdio.h> #include <stdlib.h>   #define name_length 20 #define email_length 15  struct info {     char name[name_length];     char email[email_length];     int flag; };  int createdb(char *name) {     file * file = fopen(name, "w+b");     return fclose(file); }  file *opendb(char *name) {     file* file = fopen(name, "r+b");     if(file != null) return file;     return null; }  int closedb(file *f) {     return fclose(f); }  struct info *get(file *file, int index) {     struct info* temp;     fseek(file, index*sizeof(struct info), seek_set);     fread(temp, 1, sizeof(struct info), file);     if(feof(file) != 0) return null;     return temp;  }  int put(file *file, int index, struct info *record) {     fseek(file, index*sizeof(struct info), seek_set);     int res = fwrite(record, 1, sizeof(struct info), file);     if(res) return 0;     else return eof; }  struct info *search(file *file, char *name) {     int k = 0;     struct info* temp = get(file, 0);     {          if(temp -> flag == 1 && strcmp(temp -> name,name) == 0) return temp;         k++;         temp = get(file, k);      }while(temp != null);      return temp; } 

when "put", "get" information file, working fine. but, when try search according name, getting segmentation fault (core dumped) error.

could you, please, show mistake here?

the code

struct info* temp; ... fread(temp, 1, sizeof(struct info), file); 

in get tries write sizeof(struct info) bytes uninitialised pointer temp. need allocate memory temp.

the easiest way may modify signature of get allow callers use info instance stack

int get(file *file, int index, struct info *record) {     fseek(file, index*sizeof(*record), seek_set);     fread(record, 1, sizeof(*record), file);     if(feof(file) != 0) return -1;     return 0; } 

which called like

struct info record; if (get(file, 0, &record) == -1) {     /* eof */ } 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -