473,789 Members | 2,537 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ctime(3) gives incorrect results

Hi group,

#include <stdio.h>
#include <unistd.h>
#include <time.h>

int main(void)
{
time_t t1, t2;
char *st1, *st2;

t1 = time(NULL);

if(sleep(1)) {
printf("Signal received, exiting\n");
return (1);
}

t2 = time(NULL);

printf("t1 is %lu\n", (unsigned long)t1);
printf("t2 is %lu\n", (unsigned long)t2);

st1 = ctime(&t1);
st2 = ctime(&t2);

printf("st1 is %s", st1);
printf("st2 is %s", st2);

return(0);
}

The code above gives this output:
t1 is 1183506197
t2 is 1183506198
st1 is Wed Jul 4 01:43:18 2007
st2 is Wed Jul 4 01:43:18 2007

How can it happen that two outputs of ctime(3), given two different
inputs (t1 != t2) are the same (st1 == st2) ?

Moreover, on a shell console:

$ date -r 1183506197
Wed Jul 4 01:43:17 CEST 2007
$ date -r 1183506198
Wed Jul 4 01:43:18 CEST 2007

Here date gives a correct result (i.e. the first date is one second
before the second date).

I doubt it has something to do with the compiler grouping the two calls
to time(NULL). If it's the case, how can I avoid it?

Thank you.

--
Pietro Cerutti

PGP Public Key:
http://gahr.ch/pgp
Jul 3 '07 #1
4 3383
Pietro Cerutti wrote:
Hi group,

#include <stdio.h>
#include <unistd.h>
#include <time.h>

int main(void)
{
time_t t1, t2;
char *st1, *st2;

t1 = time(NULL);

if(sleep(1)) {
printf("Signal received, exiting\n");
return (1);
}

t2 = time(NULL);

printf("t1 is %lu\n", (unsigned long)t1);
printf("t2 is %lu\n", (unsigned long)t2);

st1 = ctime(&t1);
st2 = ctime(&t2);

printf("st1 is %s", st1);
printf("st2 is %s", st2);

return(0);
}

The code above gives this output:
t1 is 1183506197
t2 is 1183506198
st1 is Wed Jul 4 01:43:18 2007
st2 is Wed Jul 4 01:43:18 2007

How can it happen that two outputs of ctime(3), given two different
inputs (t1 != t2) are the same (st1 == st2) ?
Well, you get these results because both st1 and st2 point to the same string.

ctime() returns a pointer to a statically allocated character array in which
the date/time string is stored (by asctime(), under the covers). This array is
reused with each call to ctime(), so your second call to ctime() wiped out the
string generated by the first call to ctime().

What you /should/ have done is something like....

printf("t1 is %s\n",ctime(&t1 ));
printf("t2 is %s\n",ctime(&t2 ));

If you needed to defer the printing until after both times were collected, you
should strcpy() the results of the first ctime() call to somewhere safe before
calling ctime() the second time.

HTH
--
Lew Pitcher

Master Codewright & JOAT-in-training | Registered Linux User #112576
http://pitcher.digitalfreehold.ca/ | GPG public key available by request
---------- Slackware - Because I know what I'm doing. ------

Jul 4 '07 #2
Lew Pitcher wrote:
Pietro Cerutti wrote:
>Hi group,

#include <stdio.h>
#include <unistd.h>
#include <time.h>

int main(void)
{
time_t t1, t2;
char *st1, *st2;

t1 = time(NULL);

if(sleep(1)) {
printf("Signal received, exiting\n");
return (1);
}

t2 = time(NULL);

printf("t1 is %lu\n", (unsigned long)t1);
printf("t2 is %lu\n", (unsigned long)t2);

st1 = ctime(&t1);
st2 = ctime(&t2);

printf("st1 is %s", st1);
printf("st2 is %s", st2);

return(0);
}

The code above gives this output:
t1 is 1183506197
t2 is 1183506198
st1 is Wed Jul 4 01:43:18 2007
st2 is Wed Jul 4 01:43:18 2007

How can it happen that two outputs of ctime(3), given two different
inputs (t1 != t2) are the same (st1 == st2) ?

Well, you get these results because both st1 and st2 point to the same string.

ctime() returns a pointer to a statically allocated character array in which
the date/time string is stored (by asctime(), under the covers). This array is
reused with each call to ctime(), so your second call to ctime() wiped out the
string generated by the first call to ctime().

What you /should/ have done is something like....

printf("t1 is %s\n",ctime(&t1 ));
printf("t2 is %s\n",ctime(&t2 ));

If you needed to defer the printing until after both times were collected, you
should strcpy() the results of the first ctime() call to somewhere safe before
calling ctime() the second time.

HTH
Uh, thank you!

--
Pietro Cerutti

PGP Public Key:
http://gahr.ch/pgp
Jul 4 '07 #3
Pietro Cerutti wrote:
Hi group,

#include <stdio.h>
#include <unistd.h>
#include <time.h>

int main(void)
{
time_t t1, t2;
char *st1, *st2;

t1 = time(NULL);

if(sleep(1)) {
printf("Signal received, exiting\n");
return (1);
}

t2 = time(NULL);

printf("t1 is %lu\n", (unsigned long)t1);
printf("t2 is %lu\n", (unsigned long)t2);

st1 = ctime(&t1);
st2 = ctime(&t2);

printf("st1 is %s", st1);
printf("st2 is %s", st2);

return(0);
}

The code above gives this output:
t1 is 1183506197
t2 is 1183506198
st1 is Wed Jul 4 01:43:18 2007
st2 is Wed Jul 4 01:43:18 2007

How can it happen that two outputs of ctime(3), given two different
inputs (t1 != t2) are the same (st1 == st2) ?
/* mha: off-topic non-standard functionality retained here, although
flagged. The problem does not lie with those non-standard
features, and I was too lazy to create a new example. */

#include <stdio.h>
#include <unistd.h /* mha: not a standard C header */
#include <time.h>
#include <stdlib.h /* mha: added so the error return
returns a portably defined value */
#include <string.h /* mha: added for strcpy */

int main(void)
{
time_t t1, t2;
char st1[26], st2[26]; /* mha: replaced pointers with arrays */

t1 = time(NULL);

if (sleep(1) /* mha: not a standard C function */ ) {
printf("Signal received, exiting\n");
return EXIT_FAILURE; /* mha: replaced the (1) return value */
}

t2 = time(NULL);

printf("t1 is %lu\n", (unsigned long) t1);
printf("t2 is %lu\n", (unsigned long) t2);

/* mha: below were two assignments to two pointers of a pointers to
the same static array. I have fixed that. These two lines are not
actually needed, since the calls to ctime() could be done in
the arguments to printf. */
strcpy(st1, ctime(&t1));
strcpy(st2, ctime(&t2));

printf("st1 is %s", st1);
printf("st2 is %s", st2);

return 0;
}
Jul 4 '07 #4

"Pietro Cerutti" <ga**@gahr.ch ha scritto nel messaggio news:87******** *************** ****@news.hispe ed.ch...
Hi group,

#include <stdio.h>
#include <unistd.h>
#include <time.h>

int main(void)
{
time_t t1, t2;
char *st1, *st2;

t1 = time(NULL);

if(sleep(1)) {
printf("Signal received, exiting\n");
return (1);
}

t2 = time(NULL);

printf("t1 is %lu\n", (unsigned long)t1);
printf("t2 is %lu\n", (unsigned long)t2);

st1 = ctime(&t1);
st2 = ctime(&t2);
7.23.3 Time conversion functions
1 Except for the strftime function, these functions each return a pointer to one of two
types of static objects: a broken-down time structure or an array of char. Execution of
any of the functions that return a pointer to one of these object types may overwrite the
information in any object of the same type pointed to by the value returned from any
previous call to any of them.

Here the second call of ctime overwrites the result of the first.
Try declaring st1 and st2 as arrays of chars, and to use strcpy().
char st1[26];
char st2[26];
/* ... */
strcpy(st1, ctime(&t1));
strcpy(st2, ctime(&t2));
printf("st1 is %s", st1);
printf("st2 is %s", st2);

return(0);
}

The code above gives this output:
t1 is 1183506197
t2 is 1183506198
st1 is Wed Jul 4 01:43:18 2007
st2 is Wed Jul 4 01:43:18 2007

How can it happen that two outputs of ctime(3), given two different
inputs (t1 != t2) are the same (st1 == st2) ?

Moreover, on a shell console:

$ date -r 1183506197
Wed Jul 4 01:43:17 CEST 2007
$ date -r 1183506198
Wed Jul 4 01:43:18 CEST 2007

Here date gives a correct result (i.e. the first date is one second
before the second date).

I doubt it has something to do with the compiler grouping the two calls
to time(NULL). If it's the case, how can I avoid it?
If this were the case, you could declare t1 and t2 as volatile. But
it isn't, as t1 < t2.
Jul 4 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
4266
by: Tivo Escobar | last post by:
Hi all, anybody here can tell me what exactly is returned by the standard function time() in <ctime> (or time.h). Please dont tell me it is the number of seconds since 1 Jan of 1970 GMT, cos it is not (at least not in my case!). If I pass this number to a Java program (print it using a java.util.Date() object), the result is the current date minus one hour. If I generate the current number of seconds since 1970 in a Java
2
19481
by: Oplec | last post by:
Hello, I am learning C++ using The C++ Programming : Special Edition by Bjarne Stroustrup. After reading some of his papers on his site, I came across a source code file that is used to compare timings for his Wrapper template class. In the main comment section, Mr. Stroustrup indicates that he is using a timing method published in JOOP by Andrew Koenig. I searched for the article, but was unable to find it. I would like to understand...
5
4661
by: berkay | last post by:
long num,num1; char *first; char *last; num=ilk.getTime();//gets time first=ctime(&num); cout.flush(); fflush(stdin); 1) cout<<"first:"<<first;
1
5598
by: JM | last post by:
Hello, A very simple select query (no joins) to a linked ODBC SQL Server 2000 table produces incorrect results. The right number of rows seem to be returned, but some of the columns have incorrect values. I converted the query to a pass-through, and it worked as expected. Does anybody have an idea as to why this might happen? I'd rather leave the query as Jet, because it's supposed to be updateable. I'm converting an Access 2000...
2
2956
by: Hao Xu | last post by:
Hi everyone! I think that everyone knows ctime() in glibc: The ctime(), gmtime() and localtime() functions all take an argument of data type time_t which represents calendar time. When interpreted as an absolute time value, it represents the number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC). Now I need to use the function of ctime() in linux kernel, but it
8
4213
by: B Williams | last post by:
I have been searching the internet trying to find the definition for the function time() in the standard library header <ctime>. Can someone help me with this? Thanks in advance.
4
9365
by: Gary Wessle | last post by:
Hi I am not getting current time with this program, what am I doing wrong? #include <ctime> #include <iostream> using namespace std; #define P(x) cout << #x " = " << (x) << "\n";
11
3549
by: aisling.cronin | last post by:
Hi I am using ctime to convert the following string 1144412677847 .... Please could some one to double check if they get the same result as me (The Time is Sun Nov 02 09:11:51 2031). It seems incorrect and would like a second opion. #include <time.h> #include <stdio.h>
0
1076
by: qpwang | last post by:
Dear All, I got a problem and need your help. After I converted my project (Embedded VC++ 3.0 for Pocket PC) to .NET 2005 Framework I can compile it without any error or warning. Then I ran it on iPAQ got an error "The parameter is incorrect". After debug I found the following line caused the error message:. CTime t1(1970, 1, 1, 0, 0, 0); Then I created a new MFC Smart Device Application in .NET 2005, project type:Visual C++ for...
0
9661
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9506
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10403
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10193
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9978
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6755
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5414
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5546
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3695
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.