c - 自动边界检查?

标签 c arrays string overflow buffer

我对编程很陌生,一直在学习 C。我试图生成一个简单的缓冲区溢出并能够预测结果作为练习,但在尝试这样做时,甚至无法创建溢出。我正在使用 MinGW,它似乎会自动调整我的数组以适应内容。我正在使用 -Wall 和 -Wextra 进行编译,但没有排除任何错误。这里到底发生了什么?为什么我没有出现段错误?我的 nNum 不应该被重写吗?当我随机写入不应该触摸的地方时,不应该有什么提示吗?谢谢!

#include <stdio.h>
#include <string.h>

/*  Array index - something to be sure that you're outside of szArray  */
#define SZ_LOCATION 15

int main(void)
{
    /*  Initialize array and number.  Store 1000 to number, and "hello\0" to array  */
    char szArray[6];
    unsigned short nNum = 1000;
    strcpy(szArray, "hello");

    printf("SZ_LOCATION = %i\n\n", SZ_LOCATION);

    /*  Print current contents of szArray ("hello").  Print the char at the preset index location, and the current (unchanged) value of nNum  */
    printf("szArray = %s\n", szArray);
    printf("szArray[SZ_LOCATION] = %c\n", szArray[SZ_LOCATION]);
    printf("nNum = %d\n\n", nNum);

    /*  Add 3 chars to szArray, to push it over 6 chars.  Re-print all variables  */
    strcat(szArray, "BIG");
    printf("szArray = %s\t(%I64u bytes)\nszArray[7] = %c\nnNum = %d\n\n", szArray, sizeof(szArray), szArray[sizeof(szArray) + 1], nNum);

    /*  Store a random char to the preset location in the array, way out there, and re-print its contents, with the new size of the array  */
    szArray[SZ_LOCATION] = 'h';
    printf("szArray = %s\nszArray[SZ_LOCATION] = %c\nsizeof(szArray) = %I64u\n", szArray, szArray[SZ_LOCATION], sizeof(szArray));

    return 0;
}

最佳答案

改变这个

/*  Add 3 chars to szArray, to push it over 6 chars.  Re-print all variables  */
strcat(szArray, "BIG");
printf("szArray = %s\t(%I64u bytes)\nszArray[7] = %c\nnNum = %d\n\n", szArray, sizeof(szArray), szArray[sizeof(szArray) + 1], nNum);

成为

while (1)
{
  /*  Add 3 chars to szArray, to push it over 6 chars.  Re-print all variables  */
  strcat(szArray, "BIG");
  printf("szArray = %s\t(%I64u bytes)\nszArray[7] = %c\nnNum = %d\n\n", szArray, sizeof(szArray), szArray[sizeof(szArray) + 1], nNum);
}

并监视程序的输出。

关于c - 自动边界检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21814250/

相关文章:

javascript - 是否可以使用 ForEach 根据 userInput 值更改数组

PHP:对数组进行排序

Java : String a = Integer. toString(1);创建多少个对象?

python - 按空格拆分列表列表中的字符串

c - 强制转换 void 指针地址的含义

c - 链表的 pthread 段错误 - 初学者

c++ - 如何获得忘记算术运算的警告?

java - 将随机数组列表从最大到最小排序

r - 查找一个字符串是否包含在 R 中的另一个字符串中

c - 输入多次写入输出文件 (C)