[英]When we take input in a string why size does not matter?
#include<stdio.h>`
int main() {
char b[1];
scanf("%s",b);
puts(b);
// gets(b);
// puts(b);
// gets(b);
// puts(b);
return 0;
}
output: output:
hello_world
hello_world
I expect that it should give max limit error but it didn't gave that.我希望它应该给出最大限制错误,但它没有给出。 Why?
为什么?
"give max limit error" --> C does not specify a "max limit error" required. “给出最大限制错误” --> C 没有指定所需的“最大限制错误”。
C is like riding a bicycle without training wheels. C 就像骑没有辅助轮的自行车。 If code is not well directed, it fails.
如果代码没有很好的指导,它就会失败。
Use a larger buffer and a width limit like:使用更大的缓冲区和宽度限制,例如:
char b[100];
scanf("%99s",b);
char b[1];
says to reserve one byte of memory for b
.表示为
b
保留 memory 的一个字节。
scanf("%s",b);
says to read any number of characters (until a white-space character is seen) and put them in memory starting at b
.说要读取任意数量的字符(直到看到空白字符)并将它们放入从
b
开始的 memory 中。
So this code asks to write to memory that is not reserved for b
.所以这段代码要求写入 memory,它不是为
b
保留的。 Nothing in the C language stops you from doing that. C 语言中没有任何内容可以阻止您这样做。 You are allowed by the C language to ask to do “improper” things;
C 语言允许您要求做“不当”的事情; it is deliberately a language for having low-level control of various parts of the computer.
它是一种用于对计算机的各个部分进行低级控制的语言。 The C standard does not specify what happens when you do that;
C 标准没有具体说明当你这样做时会发生什么; it is up to you, and other tools, to take care with what you are doing when you go beyond what the standard defines.
当您 go 超出标准定义的范围时,您和其他工具需要注意您正在做的事情。
If writing to that memory happens not to break anything else your program needs to continue “working,” then the program might “work.”如果写入 memory 不会破坏您的程序继续“工作”所需的任何其他内容,那么该程序可能会“工作”。 If it does break something else, the program can fail in various ways.
如果它确实破坏了其他东西,程序可能会以各种方式失败。 Also note that the C standard permits the compiler to optimize your program in ways that will not affect programs that are fully defined by the C standard but that may cause surprising effects in programs that are not fully defined by the standard.
另请注意,C 标准允许编译器以不会影响完全由 C 标准定义的程序的方式优化您的程序,但可能会对未完全由标准定义的程序产生意外影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.