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".
", 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;
}
并且期待 Segmentation Fault
,因为 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屋!