Is character array in C dynamic?

爱⌒轻易说出口 提交于 2019-12-02 07:09:28

Others have pointed out that it is undefined behaviour. What this means is that when you have char a[4] and you attempt to access anything that is out-of-bounds (e.g. a[4] = 't'), then there is no guarantee as to how your program behaves. In some cases, it may work, and in other cases, it may crash. Since there is no guarantee, it is particularly useless to depend on such code.

The problem with gets() is that you can't tell it how big the buffer is, so it has no idea when to stop writing to the supplied buffer. You entered in 11 characters, and gets has performed the equivalent of:

a[0] = 'm';
a[1] = 'e';
a[2] = 'l';
a[3] = 'w';
a[4] = 'i'; // at this point, we are writing out-of-bounds
a[5] = 'n';
/* ... etc ... */
a[12] = '\0';

In C, there are no automatic bounds checks, and there are simply no guarantees as to what will happen.

Functions that write to a buffer that cannot be limited are generally considered unsafe (unless the function is documented not to write more than a certain number of characters, etc.).

No, arrays in C are not dynamic, what you see is undefined behavior because of buffer overflow.

And this is the reason you should NOT use gets(), use fgets() instead, which would prevent buffer overflow like this.

user3217895

gets() working is undefined by the compiler anything can happen use fgets.

Check Here

gets function is dangerous to use in C. Avoid it by using fgets function.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!