[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: g++272 libs, revisited. (This is really a C question)



Bob Bernstein wrote:

> As part of a homework assignment I've written a little program to do
> arithmetic with fractions and mixed numbers, and I wanted to benchmark the
> speed of various algorithms for finding 'gcd,' the greatest common divisor.
> Not knowing how to do the timing piece, I started playing with gettimeofday.
> Here's what I came up with:
>
> #include <iomanip.h>
> #include <sys/time.h>
>
> int main()
> {
>  struct timeval *ThisTime;
>  struct timezone *huh = 0;
>  int i;
>  long int k;
>  i = gettimeofday(ThisTime, huh);
>  cout << i << endl;
>  k = ThisTime->tv_sec;
>  cout << k;
> }
> --
> Bob Bernstein
> at
> Esmond, R.I., USA      <bernie@brainiac.com>
>
> --
> Unsubscribe?  mail -s unsubscribe debian-user-request@lists.debian.org < /dev/null

Bob,I don't know much about linux, but I think there is a basic C programming
mistake.
I don't think gettimeofday points your pointers to some static memory, I think it
expects you to allocate memory for them.
Specifically man for gettimeofday says
   ***
   PROTOTYPE:
   int gettimeofday( struct timeval *tv, struct timezone *tz );
    DEFINITION:
   ...
   if either tv or tz is null the corresponding structure is not set or returned.
   ****
This means gettimeofday is expecting you to have allocated memory.  Congratulations
to gcc for linux for not letting you do so dangerous of an unitialized pointer
mistake.  Since you initialized huh to 0 (better form is to init to manifest constant
NULL) that's fine.  But ThisTime is an unitialized pointer A BIG C NO-NO!
gettimeofday will initialize to whatever memory location is pointed to by whatever is
on the stack (and interpreted as a pointer) when space is grabbed for the local data
for main.
There are two types of solution, one is dynamic memory (more responsibility for you
to clean up) or local (automatic) memory.  I took the liberty of changing your
variable to begin with lower case, since I prefer that style.

/*local (stack space) solution:*/
struct timeval thisTime;
...
i = gettimeofday( &thisTime, NULL);
...
k = thisTime.tv_sec;  /*no longer using indirection*/

/*dynamic (heap space) solution - C++*/
struct timeval *thisTime = new timeval;
...
i = gettimeofday( thisTime, NULL );
...
k = thisTime.tv_sec;
... /*assuming your program was bigger and you wanted to be frugal with memory: when
your done using 'thisTime'*/
delete thisTime;  /*Don't use thisTime anymore unless you reallocate, or you're
making a dangling pointer mistake*/

This is really a C question though, there is lots of good literature on being
VERY CAREFUL about pointers.  If your not careful someday we may all be forced to
program in JAVA so such error are no longer made  ; )
-Chip Grandits

---Your year 10K consultant, someday 4 digits wont be enough, hire me today!---


Reply to: