Search code examples
cloopsvariablesfgets

C variable changes in loop


When trying to loop through lines in a file and fetch a number in it I used the following code and the value of lnCount (used to increment in the loop) changes after the first iteration of the loop :

long nbl = nbLine(filename); // This function works fine

long *allocatedMemoryStartingPos = NULL; 
allocatedMemoryStartingPos = malloc(sizeof(long)*(nbl+1)); 

if (allocatedMemoryStartingPos == NULL) {
    exit(0); // Immediately stops the program
}

long *posPtr = &allocatedMemoryStartingPos[0];

initArrayTo0(allocatedMemoryStartingPos, nbl+1); // Works as well, sets all values 0

char str[] = "";
char spl[] = "";
long val = 0;

FILE* f = NULL;
f = fopen(filename, "r");
if (f != NULL) {
    for (long lnCount = 0; lnCount < nbl; lnCount++) {
        printf("lnCount = %ld\n", lnCount);
        getStartPosFromFile(f, 250, &val, str, spl);
        posPtr = val;
        posPtr++;
    }
}
fclose(f);
free(allocatedMemoryStartingPos);

And the code for getStartPosFromFile() is the following :

void getStartPosFromFile(FILE* f, int maxSize, long *ret, char str[], char spl[]){
    if (fgets(str, maxSize, f) != NULL) {
        strcpy(spl, extractColumn(str, 7));
        *ret = strtol(spl, NULL, 10);
    } else {
        printf("fgets failed!\n");
        perror("fgets failed!");
    }
}

In the above code, extractColumn works fine as well, it justs gets a substring of the current line and copies it into a string (spl).

The output of this code is the following :

lncount = 0
lncount = 3301218

Solution

  • str and spl are declared as 1 size character array (only terminating null). Copying more than 1 character in them invokes Undefined Behaviour (because you write in memory that can be used by other variables). From that point anything is possible...

    You must declare a size coherent with your needs:

    #define SIZE 1024
    
    char str[SIZE] = "";
    char spl[SIZE] = "";
    

    Please put a relevant value instead of my 1024 example