Nicholas Charles
Nicholas Charles

Reputation: 41

Receiving segmentation fault when using a struct with FILE type - C

I keep receiving a segmentation fault when trying to open a file through the use of fopen and a struct that contains a FILE type. New to C so sorry if this is a noob question. Code for the struct:

  typedef struct _FileInternal {
  FILE* fp;
  char mem[2];
} FileInternal;

// file handle type
typedef FileInternal* File;

Code for the file open:

File open_file(char *name) {
  File a;

  fserror=NONE;
  // try to open existing file
  a->fp=fopen(name, "r+");
  if (! a->fp) {
    // fail, fall back to creation
    a->fp=fopen(name, "w+");
    if (! a->fp) {
      fserror=OPEN_FAILED;
      return NULL;
    }
  }
  return a;
}

Trying File f; f=fopen("newfile.dat"); returns the fault

Any help is much appreciated!

Upvotes: 0

Views: 126

Answers (2)

Bernardo Duarte
Bernardo Duarte

Reputation: 4264

You have dereferencing a pointer without doing a memory allocation before, to solve this problem do this:

File open_file(char *name) {
  File a = (File) malloc(sizeof(FileInternal));

Upvotes: 0

Arkia
Arkia

Reputation: 126

File is a pointer type which makes a a pointer. a is never initialized to point to a valid FileInternal struct so dereferencing it can cause a seg fault.

Upvotes: 1

Related Questions