gpt4 book ai didi

c - 当我溢出分配的字符数组时,为什么我的 C 程序不会崩溃?

转载 作者:行者123 更新时间:2023-12-02 07:02:15 25 4
gpt4 key购买 nike

我有一个简单的 C 文件 I/O 程序,它演示了逐行读取文本文件,并将其内容输出到控制台:

/**
* simple C program demonstrating how
* to read an entire text file
*/

#include <stdio.h>
#include <stdlib.h>

#define FILENAME "ohai.txt"

int main(void)
{
// open a file for reading
FILE* fp = fopen(FILENAME, "r");

// check for successful open
if(fp == NULL)
{
printf("couldn't open %s\n", FILENAME);
return 1;
}

// size of each line
char output[256];

// read from the file
while(fgets(output, sizeof(output), fp) != NULL)
printf("%s", output);

// report the error if we didn't reach the end of file
if(!feof(fp))
{
printf("Couldn't read entire file\n");
fclose(fp);
return 1;
}

// close the file
fclose(fp);
return 0;
}

看起来我已经分配了一个数组,每行有 256 个字符的空间(在 32 位机器上为 1024 bytes 位)。即使当我在第一行用超过 1000 个字符的文本填充 ohai.txt 时,程序也不会发生段错误,我认为它会发生,因为它溢出了分配给它的可用空间量由 output[] 数组指定。

我的假设是,当操作系统有额外的可用内存时,它会为程序提供额外的内存。这意味着只有当 ohai.txt 中的一行文本消耗的内存导致计算器溢出时,程序才会崩溃。

有更多 C 和内存管理经验的人可以支持或反驳我的假设,即为什么这个程序不会崩溃,即使文本文件的一行中的字符数远远大于 256?

最佳答案

你在这里没有溢出任何东西:fgets 不会向缓冲区写入超过 sizeof(output) 个字符,因此不会溢出任何东西(见 the documentation ).

但是,如果缓冲区确实溢出,则会出现未定义的行为。根据 C 规范,程序可能会做任何事情:崩溃,不崩溃,默默地破坏重要数据,不小心调用 rm -rf/ 等。所以,不要如果您调用 UB,预计程序会崩溃。

关于c - 当我溢出分配的字符数组时,为什么我的 C 程序不会崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18470705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com