Problem with volatile modifier

From: Marcin Kalicinski (kalita_at_poczta.onet.pl)
Date: 09/30/04


Date: Thu, 30 Sep 2004 18:26:48 +0200

Hi all,

I have a problem with 'volatile' use in C++.

The function get_clocks() below tries to use a 16 bit hardware counter to
count time. The counter overflows very often. But an interrupt is generated
everytime the counter overflows, and function handler() counts these
overflows in variable n_overflows.

The problem is that during calculation of time value in get_clocks()
function (marked by *** in the code), an overflow interrupt can happen
modifying n_overflows value. This will render the calculation useless
because value read from timer and n_overflows would not correspond to the
same point of time. To prevent that I use another variable called flag. The
flag is set by the interrupt handler to inform get_clocks function that
overflow occured. The function then retries the time calculation by
rereading values from the timer (the hardware timer counter is mapped to
memory address 0x10000000).

The problem is that it does not work. Sometimes time value returned from
get_clocks() is less than the previously acquired (by roughly 2^16 what
indicates a problem with n_overflow counter). I suspect there might be
something wrong with my use of volatile modifier.

Here's the relevant code:

volatile unsigned long n_overflows;
volatile bool flag;

// Overflow interrupt handler
void handler() {
    ++n_overflows;
    flag = true;
}

// Function to get the number of clock ticks passed
unsigned long get_clocks() {
    unsigned long r;
    do {
        flag = false;
        r = n_overflows << 16 +
             *(volatile unsigned short *)0x10000000; // ***
    } while (flag);
    return r;
}

thanks,
Marcin



Relevant Pages

  • [UNIX] Cyrus Sieve / libSieve Buffer Overflow
    ... These overflows allow remote attackers to cause ... Problem comes when giving the script a>100 chars long corrupted header ... name,>100 chars long IMAP flag or a script that contains lots of errors ... to overflow the 500 char limit in error message. ...
    (Securiteam)
  • Re: cheking overflow
    ... but if the number overflows and shows negative even when actually it ... which is big enough that your routine won't overflow it. ... return from f - if it is not, then f could flag up an error somehow, ...
    (comp.lang.c)