Integer to clock format - Crash

Hello everyone!

I am supposed to test the runtime of some algorithms with diffrent complexities as a function of m. Given some values for m, I need to change m to a "clock" format you know day hr : min : sec : msec.

Here's the code for conversion:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
string format(int m)
{
    int ms;
    int ss;
    int mm;
    int dd;
    int hh;
    ms = m%1000;
    m = (m - ms)/1000;
    ss = m%60;
    m = (m - ss)/60;
    mm = m%60;
    m = (m - mm)/60;
    hh = m%24;
    dd = (m - hh)/24;
    char * charr;
    sprintf(charr, "%03d %02d:%02d:%02d:%02d", dd, hh, mm, ss, ms);     
    return charr;
}


Now I'm inputing the runtime in a text file, using the following code:
1
2
3
4
5
6
7
8
9
outData << setw(9)  << "1" << setw(8) <<
               setw(18) << format(log10(1)) <<
               setw(18) << format(sqrt(1)) <<
               setw(9)  << format(1) << setw(8) <<               
               setw(18) << format(1*log10(1)) <<
               setw(18) << format(1*1) <<
               setw(18) << format(1*1*1) <<
               setw(18) << format(2^1) <<
               setw(18) << format(fact(1)) << endl;


But for some reason the program is crashing.
What would be the problem?
Any help is appreciated!
It should have crashed on Windows, also. (You are just lucky that it didn't.)

Line 16 only allocates a pointer variable -- the pointer does not point to anything in particular. The crash likely occurs on line 17 when you try to sprintf() to some random memory location.

I do have to wonder why you are using sprintf() at all. Why not use the C++ way?

1
2
3
#include <iomanip>
#include <sstream>
#include <string> 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
string format(int m)
{
    int ms = m%1000;    m /= 1000;
    int ss = m%60;      m /= 60;
    int mm = m%60;      m /= 60;
    int hh = m%24;      m /= 24;
    int dd = m;
    ostringstream result;
    result << setfill( '0' )
           << setw( 3 ) << dd << " "
           << setw( 2 ) << hh << ":"
           << setw( 2 ) << mm << ":"
           << setw( 2 ) << ss << ":"
           << setw( 2 ) << ms;
    return result.str();
}

That said, if you must, change your line 16 to read

  16     char charr[ 17 ];

That will be implicitly-constructed into a string when you return it.

Hope this helps.
Topic archived. No new replies allowed.