自动边界检查?

时间:2014-02-16 16:47:58

标签: 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;
}

2 个答案:

答案 0 :(得分:0)

它不会调整您的数组以适应内容。通过戏剧性的巧合,超出阵列极限的寻址没有破坏任何重要的东西。更具体一点:数组是在堆栈上分配的,你写得足够远,不会弄乱临时push / pop,或者编译器决定根本不需要它们,你触摸未使用的堆栈空间。请在之后之前触摸某些以获得任何效果。

答案 1 :(得分: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);
}

并监控程序的输出。