How to return a string?

Hi,
I have a problem with a function that I wrote
1
2
3
4
5
6
7
8
9
10
11
std::string timehms(double x)
{
	char *buffer = new char[12];
	int hh, mm, ss;
	hh = int(x / (60 * 60));
	mm = int(x / 60) - 60 * hh;
	ss = int(x) - 60 * 60 * hh - 60 * mm;
	sprintf(buffer, "%6i:%2.2i:%2.2i", hh, mm, ss);
	return std::string(buffer);
	delete[] buffer;
}

On my Mac it works but on linux it doesn't in both cases I use GCC.
In my code I use the function this way cout << timehms(235.25);.
What is wrong?
Last edited on
I don't see a problem. Always add the error message you are getting.

One thing: Line 10 never runs and therefore you are leaking memory. since you know you will never need more than 12 char's, you should switch to char buffer[12]; instead of using dynamic memory.
This solved the problem. I guess it was that memory leak.
So let me get that strait. Whatever comes after return is never executed, is that right?
Never.
Well, as is often the case, I could not finish a response I began typing some time ago, so here it is...

Your buffer is not big enough for all the stuff you are sprintf()ing into it.
Also, you dynamically allocate it, but fail to free it (as you return on line 9 and control never gets to line 10).

You should switch to using a std::stringstream, but if you don't want to do that, just allocate your buffer on the stack instead of the heap:

1
2
3
4
5
6
7
8
9
10
11
12
13
std::string timehms(double x)
{
	int hh, mm, ss;
	...

	std::ostringstream ss;
	ss << setfill( '0' ) << right;
	ss << setw( 6 ) << hh << ':';
	ss << setw( 2 ) << mm << ':';
	ss << setw( 2 ) << ss;

	return ss.str();
}
1
2
3
4
5
6
7
8
9
10
std::string timehms(double x)
{
	int hh, mm, ss;
	...

	char buffer[13];
	sprintf(buffer, ...);

	return buffer;
}

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