Home > Enterprise >  Why are there extra characters in my char[]?
Why are there extra characters in my char[]?

Time:01-07

I,m trying to shorten a char[] by a specified number, and for some reason, I've got more characters in my new char[]. Can you help me fix this?

When I tried with 1 or 2 letters, the result is this: (the d, n, k, a are the first letters of each lines reversed) @▬w @▬n @▬k @▬a

(the di, an, ok, la are the first two letters of each lines reversed) @id @an @ok @la

With 3 letters, it works perfectly: nid ran rok mla

But same problem with more than 3: qp░nnid qp░aran qp░trok qp░amla And with more letters than the longest line, it also works perfectly:

eynnid scnaran etrok amla <--- These are my words backwards --->

char **read(FILE *file, int lineLength, int *pLines)
{
    size_t total = 0;
    size_t allocated = START;

    int sor = 0;

    char buffer[MAX_LENGTH];
    char shortened[lineLength];
/////////
    //printf("%d", sizeof(shortened));
    char **lines= (char **)malloc(allocated* sizeof(char *));

    while (fgets(buffer, MAX_LENGTH, file) != NULL)
    {
        for (int i = 0; i < lineLength; i  )
        {
            shortened[i] = buffer[i];
        }

        int length = strlen(shortened);
        if (shortened[length - 1] == '\n')
        {
            shortened[length - 1] = '\0';
        }
        if (line == allocated)
        {
            allocated*= 2;
            lines= realloc(sorok, allocated* sizeof(char *));
        }
        lines[line] = (char *)malloc(lineLength);

        strcpy(lines[line], shortened);
        line  ;
    }
    *pLines = line;
    return lines;
}

CodePudding user response:

One major problem is this loop:

for (int i = 0; i < lineLength; i  )
{
    shortened[i] = buffer[i];
}

If lineLength > strlen(buffer) then you will copy the null-terminator (and beyond, including data that isn't initialized by the fgets call).

But if strlen(buffer) >= lineLength you will not copy the null-terminator. Then you use the strlen function on shortened which will then go beyond the end of shortened and you will have undefined behavior.


And for a better way to remove the newline (which you need to do for buffer and not shortened) see Removing trailing newline character from fgets() input

  • Related