5

In the K&R, chapter 8, it has a custom implementation of the putc and getc functions. In the first definition of getc, if the parameter is stdin, according to the definition of _iob, the function will try to write in the address 0 because this is the value which _iob[0].ptr and _iob[0].base were assigned. Is this legal?

Code: http://ideone.com/AIkCA

Definition of _iob:

FILE _iob[20] = {
 {0, (char *) 0, (char *) 0, _READ, 0},
 {0, (char *) 0, (char *) 0, _WRITE, 0},
 {0, (char *) 0, (char *) 0, _WRITE, 0}
};
  • 9
    Why don't you post the code in your question and tell us what edition of the book are you using? I assume that not everyone here has a copy of the book handy to understand what you are talking about. – hugomg Jul 02 '12 at 14:37
  • 2
    I case of any future questions of this type, there is an errata page for K&R2 at - at least, there was. It seems to be down right now. Google cache has it though. (*enormous URL omitted*) If you found any errors not yet discovered, the C programming world will be shocked. It is called our Bible after all. We've studied it *hard*. – Alan Curry Jul 02 '12 at 15:12
  • 1
    The cm.bell-labs.com site is back up now and the link still doesn't work. Here it is again: http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html – Alan Curry Jul 02 '12 at 23:55
  • @AlanCurry is the implementation of `putc(x, p)` right? Shouldn't it be the 'opposite' of `getc()` – Tony Jul 31 '14 at 02:51

3 Answers3

0

Assuming we both 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 is initialized with cnt==0, so this definition of getc will branch to _fillbuf (without looking at (p)->ptr), and _fillbuf has special code for the fp->base == NULL case and sets both base and ptr to allocated memory.

Christopher Creutzig
  • 8,656
  • 35
  • 45
0

I'm having a hard time following what's being asked, but from the use of "custom" in the question, one angle to look at this from is whether replacing getc and putc with these definitions on an existing system is valid, and the answer is no. The example in K&R is showing you one way to go about writing the stdio library, not something that can work with an existing (possibly very different) implementation of stdio.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
0

Actually, I was wrong.

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