why does this return rubbish?

Started by
5 comments, last by Jaggy 20 years, 2 months ago
I have a function in one of my classes:

char* CTurn::ShowRoom(Player *Players, Room *Rooms)
{
	char Buffer[255];


	sprintf(Buffer, "%s the %s is in Room %i: %s.\n"
			  			  			  ,Players[m_whoToGo].getName(),Players[m_whoToGo].getPlayerTypeString()
			  		 	  			  ,Rooms[Players[m_whoToGo].getRoom()].getID()
			  			  			  ,Rooms[Players[m_whoToGo].getRoom()].getName() );


	return Buffer;
}

and I call it from my main program with cout << turn.ShowRoom(Players,Rooms); But it returns rubbish. I know my classes are set up right and the correct text is being sent to the Buffer, because using a cout in that function displays everything correctly. It just messes up when it gets returned? Anyone who can point out what I''m doing wrogn will be very much appreciated. Thanks.
Advertisement
The buffer does no longer exist at the time your caller receives the pointer to it.
To elaborate on the previous poster''s comment, you allocated your buffer on the stack. It''s ''lifespan'' ends with this stack frame. In particular, it will be gone basically immediately after exiting the function. There are many ways to get more persistent memory, but without knowing how you will use the memory (and clean it up afterwards) it is hard to recommend which is best for you. From your snippet a simple way would be to statically allocate the buffer.

oh right! Of course...I didn''t think of that.

I made it return void instead, and passed another char* variable to the function. I used strcpy on the Buffer to this variable, and it works fine now
Ta.

I''ve just tried it using static too, and that works just as well.

I think this way is best for me, it seems more intuitive and it allows me to use the function in a cout. Thank you, you clever lot.
static is dangerous too.

suppose you have a method taking 2 char*, what does method(ShowRoom(someargs),ShowRoom(otherargs)) do?

There are 2 ways to do it right: Use a class (std::string, a smartpointer or write something yourself) to store the pointer and let the destructor handle the memory-deallocation or manual memory management.
Also, check your compiler documentation. It should warn you about such misdeeds.

This topic is closed to new replies.

Advertisement