C-关闭一个错误,但没有分段错误? [英] C - Off by one error, but no segmentation fault?
问题描述
我最近在C语言中编写了此代码:
I recently wrote this code in C:
#include <stdio.h>
#define N_ROWS 100
int main() {
char *inputFileName = "triangle_data.txt";
FILE *inputFile = fopen(inputFileName, "r");
if (inputFile == NULL) {
printf("ERROR: Failed to open \"%s\".\n", inputFileName);
return -1;
}
int triangle[(N_ROWS*(N_ROWS+1))/2 - 1];
size_t size = sizeof(triangle)/sizeof(int);
size_t index;
for (index = 0; !feof(inputFile); ++index) {
fscanf(inputFile, "%d", &triangle[index]);
}
return 1;
}
,并期望出现分段错误
,因为 N_ROWS *(N_ROWS + 1))/ 2
足以容纳文件中的数据,但是如您所见,我将数组做成了一个元素较小。不知何故,这不会触发细分错误。如果我将 for
循环的主体替换为:
and was expecting a Segmentation Fault
, since N_ROWS*(N_ROWS+1))/2
is just enough space to hold the data in the file, but as you can see I made the array one element smaller. Somehow this doesn't trigger a segmentation fault. It does if I replace the body of the for
-loop with:
int tmp;
fscanf(inputFile, "%d", &tmp);
triangle[index] = tmp;
这里发生了什么。如果将数组中的三个元素缩小,它仍然不会触发分段错误。五个要素可以触发一个。我确定文件中有足够的数据。
What is happening here. If I make the array three elements to small it still doesn't trigger a segmentation fault. Five elements to small trigger one. I'm sure there is enough data in the file.
作为测试,我随后打印了该数组,如果选择较小的数组,则缺少元素。
As a test I printed the array afterwards and if I choose a smaller array there were elements missing.
PS:在OS X上与 clang
一起编译。
PS: Compiled with clang
on a OS X.
推荐答案
这是怎么回事?
What is happening here?
当您在数组对象之外进行编写时,您的程序会调用未定义的行为。 C语言中未定义的行为是未定义的,您的程序可以在今天运行,并在所有其他天内崩溃,甚至可以打印莎士比亚的完整著作。
Your program invokes undefined behavior as you are writing outside your array object. Undefined behavior in C is undefined, your program can work today and crash all the other days or even print Shakespeare complete works.
这篇关于C-关闭一个错误,但没有分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!