• Does the C standard guarantee buffers are not touched past their null terminator?


    Question:

    In the various cases that a buffer is provided to the standard library's many string functions, is it guaranteed that the buffer will not be modified beyond the null terminator? For example:

    char buffer[17] = "abcdefghijklmnop";
    sscanf("123", "%16s", buffer);

    Is buffer now required to equal "123efghijklmnop"?

    Another example:

    char buffer[10];
    fgets(buffer, 10, fp);

    If the read line is only 3 characters long, can one be certain that the 6th character is the same as before fgets was called?


    Answer:

    Each individual byte in the buffer is an object. Unless some part of the function description of sscanfor fgets mentions modifying those bytes, or even implies their values may change e.g. by stating their values become unspecified, then the general rule applies: (emphasis mine)

    6.2.4 Storage durations of objects

    2 [...] An object exists, has a constant address, and retains its last-stored value throughout its lifetime. [...]

    It's this same principle that guarantees that

    #include <stdio.h>
    int a = 1;
    int main() {
      printf ("%d
    ", a);
      printf ("%d
    ", a);
    }

    attempts to print 1 twice. Even though a is global, printf can access global variables, and the description of printf doesn't mention not modifying a.

    Neither the description of fgets nor that of sscanf mentions modifying buffers past the bytes that actually were supposed to be written (except in the case of a read error), so those bytes don't get modified.


    想要看到更多学习笔记、考试复习资料、面试准备资料? 想要看到IBM工作时期的技术积累和国外初创公司的经验总结? 敬请关注: [CSDN](https://blog.csdn.net/u013152895) [简书](https://www.jianshu.com/u/594a3de3852d) [博客园](https://www.cnblogs.com/vigorz/) [51Testing](http://www.51testing.com/?15263728)
  • 相关阅读:
    Python 标准库 urllib2 的使用细节
    为什么C++编译器不能支持对模板的分离式编译
    source insight插件
    tar命令
    绘制和重绘,有效矩形和无效矩形
    常量表达式
    区间迭代
    lambda函数
    decltype和新的返回值语法
    auto用法
  • 原文地址:https://www.cnblogs.com/vigorz/p/10499218.html
Copyright © 2020-2023  润新知