Is character array in C dynamic?

a 夏天 提交于 2019-12-31 04:42:06

问题


I have written a simple program in C. A program to input a String and display it along with the length.

#include<stdio.h>

int main()
{
char a[4];
printf("Enter the name : ");
gets(a);

printf("\nThe name enterd is : %s",a);
printf("\nLength of string is : %d",strlen(a));

getch();
return 0;
}

The program do not contain warning or error.

At run-time I entered the value " melwinsunny " as input. There was no error and the result displayed was :

Enter the name : melwinsunny

The name entered is : melwinsunny

length of string is : 11

Why is it so? I have declared the character array of length 4 ( char a[4] ). Please explain.

Does this mean the character array is dynamic?


回答1:


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.).




回答2:


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.




回答3:


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

Check Here




回答4:


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



来源:https://stackoverflow.com/questions/21250296/is-character-array-in-c-dynamic

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