-1

I am new to C programming and i am really confused on below code:

#include <stdio.h>
#include <string.h>
int main(void)
{
    char arrstr[6];
    int i;
    printf("Enter: ");
    scanf("%s",arrstr);
    printf("arrstr is %s\n",arrstr);
    printf("length os arrstr is %d\n",strlen(arrstr));
    for(i=0;i<20;i++)
    {
         printf("arrstr[%d] is %c, dec value is %d\n",i,arrstr[i],arrstr[i]);
    }
    return 0;
 }   

As from my understanding, after the declaration of arrstr[6], the compiler will allocate 6 bytes for this char array, and consider the last '\0' char, 5 valid chars can be stored in the char array.

But after i run this short code, i get below result: enter image description here

The printf shows all chars i input, no matter how long is it. But when i using an index to check the array, seems i cannot find the extra chars in the array.

Can anyone helps to explain what happened?

Thanks.

Marvin Zhang
  • 169
  • 1
  • 8

1 Answers1

0

Try changing your code by adding this line right after the scanf statement:

arrstr[5] = '\0';

What has happened is that the null character was overwritten by the user entry. Putting the null character back in manually gives you proper behavior for the next two lines, the printf statements. The for loop is another matter. C does not have any kind of bounds checking so it's up to the programmer to not overrun the bounds of an array. The values you get after that could be anything at all, as you are just reading uninitialized RAM bytes at that point. A standard way of avoiding this is to use a const int variable to declare the array size:

const int SIZE = 6;
char arrstring[SIZE];

Then also use SIZE as the limit in the for loop.

P.S. There is still a problem here with the user entry as written, because a user could theoretically enter hundreds of characters, and that would get written out-of-bounds it seems, possibly causing weird bugs. There are ways to limit the amount of user entry, but it gets fairly involved, here are some stackoverflow posts on the topic. Keep in mind for future reference:

Limiting user entry with fgets instead of scanf

Cleaning up the stdin stream after using fgets

neutrino_logic
  • 1,289
  • 1
  • 6
  • 11
  • @MarvinZhang Sure, note also the edit. User input in C programs is notoriously buggy for several reasons, so you could still have problems, with overwritten memory and clogged input buffers needing flushing. Those links give all the gory details. – neutrino_logic Sep 23 '19 at 04:46