zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    理解Device Tree Usage
    Unhandled Exception in EL3
    python的multitask模块安装
    利用python制作在线视频播放器遇到的一些问题
    设置linux代理完成apt-get
    Eric6安装问题解决
    关于代码重构的比喻
    AAC的RTP封装中的AU头分析
    CORE DUMP生成调试
    开源库SRT编译指南
  • 原文地址:https://www.cnblogs.com/vigorz/p/10499218.html
Copyright © 2011-2022 走看看