Question

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?

Was it helpful?

Solution 2

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

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top