Does fgets() always null-terminate the string it returns?

后端 未结 2 1176
庸人自扰
庸人自扰 2021-01-24 07:50

Is this safe to do? Does fgets terminate the buffer with null or should I be setting the 20th byte to null after the call to fgets and before I call

2条回答
  •  别那么骄傲
    2021-01-24 08:10

    If there is an error, fgets() may or may not store any zero bytes anywhere in the buffer. Code which doesn't check the return value of fgets() won't be safe unless it ensures there's a zero in the buffer somewhere; the easiest way to do that is to unconditionally store a zero to the last spot. Doing that will mean that an unnoticed error may (depending upon implementation) cause a bogus extra line of data to be read, but won't fall off into Undefined Behavior.

提交回复
热议问题