Search code examples
centab-detab

C: character comparison fails


After succesfully running an entabulator, my detabulator won't pick up on a character comparison that should exit a while loop. After trying "0(tab)8(enter)(ctrl+D)" as input the tab is written correctly as spaces, but after rp is incremented to point to the 8, the while loop that should read the 8 won't exit and I get a seg fault. Here's the code:

#include <string.h>
#include <stdio.h>
#define MAXLINE 100
char doc[9001];
main(int argc, char *argv[])
{
    int max = 0;
    char *rp = doc;
    char *wp = rp;
    char *tf = wp;
    char *lp = doc;

    while ((*(rp++) = getchar()) != EOF);
    *--rp = '\0';
    rp = doc;
    j = 0;
    while  ( (*rp != '\0') && (argc == 1)) {
        if (*rp == '\n') {
            lp = rp + 1;
            *wp++ = *rp++;
        }

        while( (*rp != '\t') && (*rp != '\0') && (*rp != '\n') ) { /*this loops after a tab*/
            *wp++ = *rp++;
        }
        if (*rp == '\t') {
            rp++;
            tf = lp + ((((wp - lp) / 8) + 1) * 8);
            while ((tf - wp) != 0) 
                *wp++ = 's';
        }
    }
    if (*rp == '\0')    
        *wp = '\0';
    printf("%s\n", doc);
}

Solution

  • What I feel is, the below loop is going into infinite loop.

    while( (*rp != '\t') && (*rp != '\0') && (*rp != '\n') ) { /*this loops after a tab*/
        *wp++ = *rp++;
    

    This is because, you are checking for rp!= '\t' and so on, but here

    if (*rp == '\t') 
    {
        rp++;
        tf = lp + ((((wp - lp) / 8) + 1) * 8);
        while ((tf - wp) != 0) 
            *wp++ = 's';
    }
    

    you are filling the doc array with char 's' and which is over writing '\t' also, so the above loop is going to infinite.