Zora
Zora

Reputation: 81

Writing a Code to Indent Code

My goal is to write a C program that indents the C code given in char *input. The style of one level of indentation is given in the string const char *pad. I've wrote the following code, which works find in my head but doesn't in practice. There must be a mistake somewhere, but I can't find it. Also, I can't figure out why Valgrind doesn't like the line containing while(...). Invalid read of size 1...

Any { increases the indentation level by one, and any } decreases the indentation level by one. No other indentation rules are applied. I assume there are no curly brackets inside string literals.

char *indent(char *input, const char *pad)
{
    int lenpad = strlen(pad);
    int inlen = strlen(input);
    char *output = malloc(inlen+lenpad*90); //Here I'm praying +lenpad*90 is enough
    int indent = 0; 
    int i = 0;
    int j = 0;
    int ndx;
    int ondx;
    char current = 'a';
    int n;

    for(ndx=ondx=0; ndx<inlen; ndx++){
        current = input[ndx];
        if(current == '{') indent++;
        if(current == '\n'){
            output[ondx++] = '\n';
            n = ondx;
            while(input[n] != '\n' && input[n] != '\0'){ //Trying to check if the line to come has a curly bracket.
                if(input[n] == '}') //If it does, don't indent that line anymore.
                    indent--;
                n++;
            }
            for(j=0; j<indent; j++){
               for(i=0; i<lenpad; i++){
                output[ondx++] = pad[i];
                } 
            }
        }
        else{
            output[ondx++] = current;
        }
    }
    free(input);
    output[ondx] = '\0';
    return output;
}

Instead of:

int main(void) {
    printf("asdfasdf\n");
    while (1)
    {
        while (2) {
            printf("printsomething\n");
        }
    }
}

My code gives:

int main(void) {
        printf("asdfasdf\n");
        while (1)
        {
            while (2) {
                printf("printsomething\n");
            }
            }
            }

Upvotes: 3

Views: 7159

Answers (2)

user12205
user12205

Reputation: 2702

Change your line

n = ondx;

to

n = ndx + 1;

You want n be the index of the next item in the input, not the output.

Upvotes: 2

Serge Ballesta
Serge Ballesta

Reputation: 149175

In a code beautifier as the one you are trying to write, you must :

  • swallow (do not output) all initial white spaces in a line (following a \n)
  • replace them by the proper indentation computed as you do from the number of { and }

Implement it and ask here if you cannot make it work

Upvotes: 3

Related Questions