0

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!

  • See [Is it a good idea to `typedef` pointers?](http://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers) Consider this an exhibit for the prosecution — the answer is "No" (unless perhaps you're dealing with function pointers). – Jonathan Leffler Sep 17 '17 at 19:34
  • Also note that names starting with an underscore and followed by either another underscore or a capital letter are reserved for any use by the implementation. Don't create names starting with underscores (simplistic but safe). Or read the full rules in §7.1.3 Reserved identifiers in the C standard, and similar sections in related standards (e.g. POSIX). – Jonathan Leffler Sep 17 '17 at 19:36
  • It is not a good idea to typedef pointers as ot makes code unreadable (you do know what is the pointer, what is the actual object etc as it doe not come from the declaration). The only exception are function pointers. – 0___________ Sep 17 '17 at 19:52
  • @JonathanLeffler: At file-scope, _every_ name starting with an underscore is reserved. – too honest for this site Sep 18 '17 at 00:23

2 Answers2

1

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.

Arkia
  • 126
  • 2
  • 4
0

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));
Bernardo Duarte
  • 4,074
  • 4
  • 19
  • 34