gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:54:58 25 4
gpt4 key购买 nike

下面的 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/

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