Ata Ata - 3 months ago 45
C Question

Exception thrown at (ntdll.dll) in Parser.exe: Access violation reading location

So, this is the chapter that is bugging me so far

void CNCread(fPointer){
printf("\n");
fPointer = fopen ("CNCG.txt", "r");
char line[30];
while(!feof(fPointer)){
fgets( line, 150, fPointer);
puts(line);
}
fclose (fPointer);
return;
}


i get the following error after compiling, running and executing this function:

Exception thrown at 0x00007FFCA1DEEAC5 (ntdll.dll) in Parser.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.

i just converted this project from Code::Blocks to Visual Studio 2015, added legacy_stdio_definitions.lib and etc so thats not the problem either, but the code worked fine with code::blocks.
Thanks to everyone in advance.

sps sps
Answer

First, char line[30] can contain maximum 30 chars, but you are trying to write more than that into it by doing fgets( line, 150, fPointer);.

Also, you are not checking if fopen succeded or failed. And you should also check if fgets succeded or failed.

Also, you can declare fPointer inside your function, instead of having it as a funciton parameter. It should be of type FILE *.

void CNCread(/* fPointer */){
    printf("\n");
    FILE *fPointer = fopen ("CNCG.txt", "r");

    /* Check if fopen succeded */
    if (fPointer == NULL) {
        fprintf(stderr, "Error: Cannot open file to read\n");
        /* Some code */
        return;
    }

    char line[30];
    while(!feof(fPointer)){
        /* You are writing more chars to line than its capacity */
        /* fgets( line, 150, fPointer); */
        /* Change it to write at max 30 chars to line */
        if (fgets( line, 30, fPointer) != NULL)
            puts(line);
    }
    if (fclose(fPointer) == EOF) {
        fprintf(stderr, "Error: Cannot close the file after reading\n");
        /* Some code */
        return;
    }

    return;
}
Comments