-1

enter image description hereThe code for output is shown in scren shot..please correct me if i am wrong(GLOBAL DECLARATION OF CHAR ARRAY)

#include<stdio.h>
char name[10];  /* though allocated memory is 10 bytes still it accepts more then 10 chars*/
void main()
{
     printf("\n ENter name :\t");
     scanf("%s",name);
}

Second case:(LOCAL DECLARATION OF CHAR array)

#include<stdio.h>
void main()
{
     char name[10];/* Now it will only accepts 10 chars NOT MORE */ 
     printf("\n ENter name :\t");
     scanf("%s",name);
}

why there is difference in acceptance of the chars in 1st case it accepts more than 10 but in 2nd exactly 10 but not more.I dont know why,but it happens???

MD XF
  • 7,860
  • 7
  • 40
  • 71
alpha9eek
  • 1,439
  • 3
  • 11
  • 10

3 Answers3

2

In both case entering string more than 10 chars (including \0) will invoke undefined behavior because you are writing past to array bound (allocated memory).
In this case, saying that first worked and second doesn't for more than 10 chars is meaningless. Any expected or unexpected behavior can be seen.

haccks
  • 104,019
  • 25
  • 176
  • 264
1

C does not do bounds checking on array accesses, so it won't automatically raise an exception if you write past the end of the array. The behavior of writing past the end of the array is undefined; the compiler is not required to handle that error in any particular way. A really smart compiler may issue a diagnostic and halt translation. Or it may compile the code as though nothing's wrong (which is the usual behavior). When run, your code may crash immediately, or it may continue to run in a bad state and crash later (been in that movie before; not fun), or it may continue to run without any issues at all.

The C language assumes you know how big your arrays are, and that you are smart enough to not wander outside of their boundaries. It won't prevent you from doing so, but at that point it makes no guaratees about your program's behavior.

John Bode
  • 119,563
  • 19
  • 122
  • 198
0

When you write more than 10 characters into name, you are stepping on unauthorized memory.

When n is defined in the global namespace you are corrupting some memory locations but bad side effects are not visible right away in your particular case. Since the behavior is undefined, for a different use case, you might see the bad side effects right away or in a delayed fashion.

When n is defined in the function, you are corrupting local stack memory and the bad side effects are visible right away in your particular case.

R Sahu
  • 204,454
  • 14
  • 159
  • 270