Strings with undetermined size

Started by
12 comments, last by UnknownPlayer 21 years, 2 months ago
I want to keep the same basic syntax as printf, but I also want to proof against getting exceptions from boundary violations.
##UnknownPlayer##
Advertisement
Well, Boost Format has a pretty similar syntax for printf. Taken from the site:

  cout << boost::format("writing %1%,  x=%2% : %3%-th try") % "toto" % 40.23 % 50;     // prints "writing toto,  x=40.230 : 50-th try"  

And no worries about breaking boundaries.
Well I think I''ve found a reasonable solution to the problem, not neat and clean but reasonable and functional for its intended purposes. The problem is I''ve now introduced some problem which is causing my strings to get their boundaries overwritten and I''m not quite sure where - this is the full function code:


  void CText::ChangeText(const char* Text, ...){	delete String;	if (Text == null)	{		String = null;		return;					// Nothing to do, get out early.	}	va_list arglist;			// Set up variable argument list		// Is this probably the first initialization of this object?	if (LargestTextSize == 0)	{		LargestTextSize = strlen(Text) + 1;		LargestTextSize *= 2;		// Multiply by two to give us a reasonable working space	}	String = new char[LargestTextSize];		// Create a new string for us	int Count = LargestTextSize * 2;		// Create a number so huge we can''t possibly not write it	va_start(arglist, Text);	// Try and output to the buffer we just created.	// If we fail, then resize it and try again.	int outval = 0;							// We''ll never be trying 0 length strings	while (outval <= 0)	{		outval = _vsnprintf(String, Count, Text, arglist);				// We need this seeming redundancy for optimization		if (outval <= 0)		{			LargestTextSize *= 2;			// Double the buffer size			Count *= 2;						// Needs to increase as well			delete String;					// Delete the string we had			String = new char[LargestTextSize];		// Create one to the new size		}				if (String == null)		{			return;		}	}	va_end(arglist);	// We have the string successfully stored	// Resize LargestTextSize for the next round	LargestTextSize = strlen(String) + 1;}[/source  
##UnknownPlayer##
quote:
delete String;

You must use delete [] String. What you allocate with new [] should be deleted with delete [].

This topic is closed to new replies.

Advertisement