Search code examples
cfopen

Segmentation fault in C in K&R fopen and fillbuf


I'm quite new to C. I faced a problem while studying the last chapter of K&R.

I'm trying to implement fopen() and fillbuf() function by using system calls, open and read.

I exactly copied the source code from the book but repeatedly get segmentation error after I compile.

    fp->fd = fd;
    fp->cnt = 0;
    fp->base = NULL;
    fp->flag = (*mode=='r')? _READ : _WRITE;

Why does error occur? Here is my complete code.

#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#define PERM 0644
#define EOF (-1)
#define BUFSIZE 1024
#define OPEN_MAX 20

typedef struct _iobuf{
    int cnt;
    char *ptr;
    char *base;
    int flag;
    int fd;
} myFILE;

enum _flags {
    _READ   = 01,
    _WRITE  = 02,
    _UNBUF  = 04,
    _EOF    = 010,
    _ERR    = 020
};

myFILE _iob[OPEN_MAX]={
    {0, (char *) 0, (char *) 0, _READ, 0 },
    {0, (char *) 0, (char *) 0, _WRITE, 1 },
    {0, (char *) 0, (char *) 0, _WRITE | _UNBUF, 2 }
};

#define stdin (&_iob[0])
#define stdout (&_iob[1])
#define stderr (&_iob[2])

#define getc(p)     ( --(p)->cnt>=0 ? (unsigned char) *(p)->ptr++ : _fillbuf(p) )

int _fillbuf(myFILE *fp)
{
    int bufsize;

    if((fp->flag & (_READ|_EOF|_ERR))!=_READ)
        return EOF;

    bufsize=(fp->flag & _UNBUF)? 1 : BUFSIZE;

    if(fp->base==NULL)
        if((fp->base=(char *)malloc(bufsize))==NULL)
            return EOF;

    fp->ptr=fp->base; 
    fp->cnt=read(fp->fd, fp->ptr, bufsize);

    if(--fp->cnt<0){
        if(fp->cnt == -1)
            fp->flag |= _EOF;
        else
            fp->flag |= _ERR;
        return EOF;
    }
    return (unsigned char) *fp->ptr++;  
}

myFILE *myfopen(char *name, char *mode)
{
    int fd;
    myFILE *fp;

    if(*mode!='r' && *mode!='w' && *mode!='a')
          return NULL;
    for(fp=_iob; fp<_iob+OPEN_MAX; fp++)
        if((fp->flag & (_READ | _WRITE))==0)
            break;

    if(fp>=_iob+OPEN_MAX)
        return NULL;

    if(*mode=='w')
         fd=creat(name, PERM);
    else if(*mode=='a'){
        if((fd=open(name, O_WRONLY, 0))==-1)
            fd=creat(name, PERM);   
        lseek(fd, 0L, 2);
    } else
        fd=open(name, O_RDONLY, 0);

    if(fd==-1)
        return NULL;

    fp->fd = fd;
    fp->cnt = 0;
    fp->base = NULL;
    fp->flag = (*mode=='r')? _READ : _WRITE;

        return fp;    
    } 

int main(int argc, char *argv[])
{
myFILE *fp;
int c;

if((fp=myfopen(argv[1], "r"))!=NULL)
    write(1, "opened\n", sizeof("opened\n"));

    while((c=getc(fp))!=EOF)
        write(1, &c, sizeof(c));

    return 0;
}

Solution

  • EDIT: Please see Jonathan Leffler's answer. It is more accurate and provides a better diagnosis. My answer works, but there is a better way to do things.

    I see the problem.

    myFILE *fp;
    
    if(*mode!='r' && *mode!='w' && *mode!='a')
          return NULL;
    for(fp=_iob; fp<_iob+OPEN_MAX; fp++)
        if((fp->flag & (_READ | _WRITE))==0) // marked line
            break;
    

    When you reach the marked line, you try to dereference the fp pointer. Since it is (likely, but not certainly) initialized to zero (but I should say NULL), you are dereferencing a null pointer. Boom. Segfault.

    Here's what you need to change.

    myFILE *fp = (myFILE *)malloc(sizeof(myFILE));
    

    Be sure to #include <malloc.h> to use malloc.

    Also your close function should later free() your myFILE to prevent memory leaks.