Search code examples
cvalgrind

Conditional jump or move depends on uninitialized value(s) when checking with if condition


int t_parse(char* target, FILE* fp) 
{   
char cuts = ':';
char * tok;
char ln[BUFF_SIZE];

if (lnCnt == 0) 
{
    lnCnt = 1;
}

while (!feof(fp)) 
{   
    int i = 0;
    int hop = 1;
    char c;
    while (hop) 
    {
        c = fgetc(fp);
        if (feof(fp)) 
        {
            if (i == 0) 
            {
                return 0;
            }
            ln[i] = '\0';
            hop = 0;
        }
        else if (c == '\n') 
        {
            ln[i] = '\0';
            hop = 0;
        }
        else if (i == BUFF_SIZE) 
        {
            fprintf(stderr, "%i: Error of long line\n", lnCnt);
            exit(1);
        }
        if (hop) 
        {
            ln[i] = c;
        }
        i++;
    }

    if (ln[0] != '#' && ln[0] != '\t' && ln[0] != '\0') 
    {   
        tok = strtok(ln, &cuts);
        if (tok == NULL) 
        {
            fprintf(stderr, "%d: Error of invalid target\n", lnCnt);
            exit(1);
        }
        else 
        {
            strcpy(target, tok);

            for (int j = 0; j < BUFF_SIZE; j++) 
            {
                if (target[j] == ' ') 
                {
                    target[j] = '\0';
                    return lnCnt++;
                }
            }
            return lnCnt++;
        }
    }
    lnCnt++;
}       
return 0;
}

After running Valgrind Conditional jump or move depends on uninitialized value(s) ==2469== at 0x10938F: t_parse (text_parsing.c:81)

Which is else { strcpy(target, tok);

            for (int j = 0; j < BUFF_SIZE; j++) 
            {
                if (target[j] == ' ') 
                {
                    target[j] = '\0';
                    return lnCnt++;
                }

line 81 is if (target[j] == ' ') I am check here so I am not sure why is there a memory leak? i ran the command valgrind --leak-check=yes --track-origins=yes --read-var-info=yes 537make


Solution

  • tok is string copied into target. It will be terminated with a '\0' character.

    Then you are looping through the characters in target, and will terminate on a matching space character. However, you are moving beyond the end of the string in target in the case when no space character is found, which is uninitialised and could contain anything--so valgrind warns you of this.

    One other issue: char *strtok(char *str, const char *delim); In this, delim points to a string of delimiters, not a single character. So char cuts = ':'; should be char *cuts = ":";