Search code examples
arrayscfor-loopscanfc-strings

Do strings in C language change in the middle of program execution?


I was writing the code for Bit stuffing, but I am not getting appropriate answer, when I checked the values of the input string, there was another garbage value added at the end of the string.

#include<stdio.h>
#include<string.h>
void input(char[],int);
void stuff(char ch[],int n)
{
    char str1[6]="11111";
    char str2[6]="00000";
    printf("str1=%s\n",str1);
    printf("ch=%s\n",ch);
        if(!strcmp(ch,str1))
        {
            printf("\n111101");
        }
        else if(!strcmp(ch,str2))
        {
            printf("\n000010");
        }
        else
        {
            puts(ch);
        }
}
void main()
{
    int flag=0;
    char ch[5];
    input(ch,5);
    printf("ch0=%s\n",ch); //printing the input string
    for(int i=0;i<5;i++)
     {
       if((ch[i]!='0')&&(ch[i]!='1'))
       {
           flag=1;
       }
    }

   if(flag==0)
    {
        puts("Entered data:");
        for(int i=0;i<5;i++)
        {
            printf("%c",ch[i]);
        }
        puts("\nAfter stuffing");
        printf("ch1=%s\n",ch);    //getting garbage value here
        stuff(ch,5);
    }
    else
    {
         printf("Enter a valid data\n");
    printf("%d",flag);
    }

}
void input(char ch[],int n)
{
    printf("Enter 5 digits\n");
    for(int i=0;i<=n;i++)
    {
        scanf("%c",&ch[i]);
    }

}

The output of the code is as follows.

Enter 5 digits
11111
ch0=11111

Entered data:
11111
After stuffing
ch1=11111♣
str1=11111
ch=11111♣
11111♣

Process returned 0 (0x0)   execution time : 4.046 s
Press any key to continue.

I am using Code blocks IDE with MINGW. The code above should compare the string entered with the given sequence and stuff the bits if all five bits are homogenous.


Solution

  • Lack of null-byte:

    A string in C is an array of null-terminated bytes. You do not terminate ch in the input function.

    strcmp does compare two strings, but it requires them to be null-terminated.

    printf too requires a null-terminated string with the %s format specifier, otherwise it doesn't know when to stop printing. And your code would most probably result in a segmentation fault.

    Accessing memory out of bounds:

    This line:

    for(int i=0;i<=n;i++)
    

    invokes undefined behaviour because it's writing to out of bounds memory. ch has been declared to only contain 5 bytes, which must include the '\0' character.