C语言

作者: 恒忏 | 来源:发表于2018-01-19 17:59 被阅读0次
    int length = rand();
    int* arr = (int *)malloc(sizeof(int) * length);
    
    //字符数组与字符串等价(c++中不是)
    //字符数组赋值时如果字符数大于数组长度,则按语法错误处理(?);
    //若小于数组长度,则多余的元素自动定为空字符(即 '\0' )。
    char str[10]="okokok";
    //char str[ ]="I am happy";
    //char* str="I love China";
    //char* a;a="I love China";
    //字符串被视为字符数组. 赋值给a的是数组的(首字符)地址
    //数组变量本身就可用作地址.不需要再进行取地址运算:&
    

    字符串连接函数

    char *strcat(char *dest, const char *src);
    

    如果结果超出str1 的长度,就是bug. crash.
    即使没有crash 也算是bug.

    The strcat() function appends the src string to the dest string, overwriting the terminating null byte ('\0') at the end of dest, and then adds a terminating null byte. The strings may not overlap, and the dest string must have enough space for the result. If dest is not large enough, program behavior is unpredictable;
    buffer overruns are a favorite avenue for attacking secure programs.


    以下是机翻:
    所述的strcat()函数追加SRC字符串到DEST串中,在端部覆盖终止空字节(“\ 0”) DEST,然后添加终止空字节。这些字符串可能不重叠,并且dest字符串必须有足够的空间用于结果。如果 dest不够大,程序行为是不可预测的; 缓冲区溢出是攻击安全程序的最佳途径。

    其中"这些字符串可能不重叠" 我认为应该翻译为:两个字符串不应该重叠.
    以上信息中最重要的就是:目标变量必须有足够大的空间,否则结果不可测!
    C 语言的指针存在潜在的重大安全隐患(先天不良),在编译阶段难以检查到这种错误!


    推论:应该建立这样的观念: 在 C 语言中任何变量的大小都是固定的. 即:不存在占用内存大小可变的变量! 没有 List , 没有 Dictionary.
    既使有所谓的字符串,也应该理解为字符数组, 而且其占用的内存空间大小固定!

    相关文章

      网友评论

          本文标题:C语言

          本文链接:https://www.haomeiwen.com/subject/fvzooxtx.html