C: Access Violation after numerous uses of fseek


My program goes through this section of my code many times without a problem. Then, in the middle of the file, the file pointer gets set to placeholder (the original address is erased) and i get an access violation when trying to fseek backwards by 1 character.

I debugged it several times and there does not appear to be any places where i wiped out the file pointer or set it to another value before coming to this fseek. As i said before, this section of my code runs many times without a problem, but this error seems very random and i can not think of a reason why it is happening.

Is there a limit on the number of times you can use fseek? Do i need to do something else if i plan to use it a lot? Will a certain number of uses wipe out the value of the file pointer?

I am not fseeking from the beginning of the file or anything crazy like that, it is smack dab in the middle and i am only trying to move back one character.

Exception thrown at 0x77A460C5 (ntdll.dll) in Hw04.exe: 0xC0000005: Access violation writing location 0x656D6F87.

ch = fgetc(input);
if (isInvisibleChar(ch) || isalpha(ch) || isdigit(ch) || ch == EOF) {
    if (id == getId(".")) {
        emit(11, 0, 3);
        strcpy(token, ".");
    printf("%s\t%d\n", token, id);
    sprintf(temp, "%d ", id);
    strcat(lexemeList, temp);
    sprintf(temp, "%s ", names[id - 1]);
    strcat(symbolList, temp);
    foundTok = 1;
if (!isInvisibleChar(ch)) {
    fseek(input, -1L, SEEK_CUR); //<-----------The Access Violation is here

note - This problem happens with and without the if statement around the fseek

asked on Stack Overflow Jul 23, 2020 by hancholo • edited Jul 23, 2020 by hancholo

1 Answer


Based on the access violation address (all valid ascii characters), I'm 100% certain that you are experiencing memory corruption somewhere.

You're using a lot of strcpy and sprintf. The first thing I recommend is that you use strncpy and snprintf. I also recommend that any buffers you use, double or quadruple their size, as it's clear however much space you allocated wasn't enough.

Memory corruption bugs are inherently difficult to predict - the reason why it's occurring so randomly is because there is a condition occurring outside the bounds of a typically running program. Here's the wiki page for memory corruption if you need a refresher:


answered on Stack Overflow Jul 23, 2020 by Roguebantha

User contributions licensed under CC BY-SA 3.0