c - 为什么数组可以存储比应有的更多的数据?

标签 c

下面的 C 代码有 char str[3]; 并且它应该只存储 3 个字符,对吗?

但是,当我编译并运行该程序时,它似乎可以存储更多内容。

当我输入明显超过 3 个字符的“ABCDEFGHIJKLMNOPQRSTUVWXY”时,我才收到“段错误”错误。

我可以知道为什么吗?

p/s:是的,我知道“gets”函数很危险,不建议使用。我只是好奇为什么它可以保留比应有的更多的数据。

user@box:~/c$ cat -n putsgets.c 
     1  #include <stdio.h>
     2
     3  int main()
     4  {
     5          char str[3];
     6          puts("Enter a line of text: ");
     7          gets(str);
     8          puts("\nYou entered: ");
     9          puts(str);
    10          return 0;
    11  }
user@box:~/c$ 
user@box:~/c$ gcc putsgets.c -o putsgets
putsgets.c: In function ‘main’:
putsgets.c:7:2: warning: implicit declaration of function ‘gets’ [-Wimplicit-function-declaration]
  gets(str);
  ^~~~
/tmp/cclFmZp2.o: In function `main':
putsgets.c:(.text+0x1f): warning: the `gets' function is dangerous and should not be used.
user@box:~/c$ 
user@box:~/c$ ./putsgets 
Enter a line of text: 
ABC

You entered: 
ABC
user@box:~/c$ ./putsgets 
Enter a line of text: 
ABCD    

You entered: 
ABCD
user@box:~/c$

下一步

user@box:~/c$ ./putsgets 
Enter a line of text: 
ABCDE     

You entered: 
ABCDE
user@box:~/c$ ./putsgets 
Enter a line of text: 
ABCDE

You entered: 
ABCDE
user@box:~/c$ ./putsgets 
Enter a line of text: 
ABCDEF

You entered: 
ABCDEF

user@box:~/c$ ./putsgets 
Enter a line of text: 
ABCDEFGHIJKLMN

You entered: 
ABCDEFGHIJKLMN

最后,当我输入ABCDEFGHIJKLMNOPQRSTUVWXY(最后一行)时发生了段错误错误

user@box:~/c$ ./putsgets 
Enter a line of text: 
ABCDEFGHIJKLMNOPQRSTU

You entered: 
ABCDEFGHIJKLMNOPQRSTU
user@box:~/c$ ./putsgets 
Enter a line of text: 
ABCDEFGHIJKLMNOPQRSTUVWXYZ

You entered: 
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Segmentation fault
user@box:~/c$ ./putsgets 
Enter a line of text: 
ABCDEFGHIJKLMNOPQRSTUVWXY   

You entered: 
ABCDEFGHIJKLMNOPQRSTUVWXY
Segmentation fault
user@box:~/c$ 

最佳答案

您可能知道,C 不检查内存安全。不过,像 valgrind 这样的实用程序确实可以提供帮助。

您的操作系统为您的程序提供的内存比其请求的多一点,并且只有当您超出该内存之一时它才会发现段错误。

How does a segmentation fault work internally (kernel/hardware)?

关于c - 为什么数组可以存储比应有的更多的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44298298/

相关文章:

c - valgrind 报告未释放的 block

c - 如何将数据库附加到可执行文件

C - 因一个错误而关闭

c - 多次使用 realloc()

c++ - 带有双移位和以下移位运算的 C/C++ 除法

c - webkit加载注入(inject)图片内容

c - 如何将整数分配给c中的指针?

c - 使用 getchar() 和 putchar() 复制文件

c - 文字 int 到 void *

c - 文件(尤其是音频文件)在内部是如何组织的?