我对编程很陌生,并且一直在研究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/