Is the implementation of getc and putc K & R implemented correctly?

Chapter 8 of K & R has a custom implementation of putc and getc functions. In the first definition of getc, if the stdin parameter, as defined by _iob, the function tries to write to address 0, because it is the value that _iob [0] .ptr and _iob [0] .base were assigned. Is it legal?

Code: http://ideone.com/AIkCA

_Iob definition:

FILE _iob[20] = {
 {0, (char *) 0, (char *) 0, _READ, 0},
 {0, (char *) 0, (char *) 0, _WRITE, 0},
 {0, (char *) 0, (char *) 0, _WRITE, 0}
};
+5
source share
3 answers

Suppose we have the same code in front of us, the answer is no.

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

stdin cnt==0, getc _fillbuf ( (p)->ptr), _fillbuf fp->base == NULL base ptr .

+1

, , - "" , , getc putc , - . K & R stdio, , (, ) stdio.

0

, .

In the first call to getc (stdin), the counter will be 0, so - (p) → cnt will not> = 0, so _fillbuf will be called. Then fillbuf will allocate a buffer, and then it will read from stdin using the read command (fp-> cnt = read (fp-> fd, fp-> ptr, bufsize).

0
source

All Articles