Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding source of garbage value [duplicate]

Tags:

c

garbage

So I've made a custom code to remove spaces from a string. But when I ran it, if there's no input, the second string will give 3 garbage values, and if there are too many spaces, the code will sometimes add a space string on its own. I just can't find where the three garbage values come from :(

#define SIZE 200
int main ()
{
    int w=0, z=0, x=0, y=0, z0, rDlength=0, Dlength=0, RandomChar, Dx=0, Dy=0;
    char rstring[SIZE], string[SIZE];
    srand(time(NULL));

    //debug
    int space=0;

    printf("Input Text: ");
    gets(rstring);
    strupr(rstring);
    strlen(rstring);
    rDlength=strlen(rstring);

    //debug
    printf("%d\n", rDlength);

    w=-1; 
    for(z=0;z<=rDlength;z++)
    {    if(rstring[z]==' ')
         {   space++;
             continue;
         }
         else if(rstring[z]=='\0')
             break;
         else if(rstring[z]!=' ')
             string[++w]=rstring[z];
    }

    //debug
    printf("%d\n", space);

    Dlength=strlen(string);

    for(z=0;z<rDlength;z++)
        printf("%c", rstring[z]);
    printf("\n");

    for(z=0;z<Dlength;z++)
        printf("%c", string[z]);
    printf("\n");

    printf("String length is %d\n", Dlength);
    return 0;
}

If there's at least 3 input characters, then the garbage value seem to disappear. but if there's only two or one character, then the garbage values appear.

like image 213
Felix Wright Avatar asked May 19 '26 09:05

Felix Wright


1 Answers

When you add characters to string, you aren't adding a terminating null character. So any elements of string past that are uninitialized. Calling strlen then reads those uninitialized characters resulting in undefined behavior.

After copying the characters, add the null terminator to the end:

for(z=0;z<=rDlength;z++) {
    if(rstring[z]==' ') {
        space++;
        continue;
    }
    else if(rstring[z]=='\0')
        break;
    else if(rstring[z]!=' ')
        string[++w]=rstring[z];
}
string[++w]='\0';
like image 91
dbush Avatar answered May 21 '26 00:05

dbush