Avoid stack based string buffers like the plague

This week I was directed to a crash in the VRML exporter. This exporter has been with 3dsmax for ages. The crash report was quite direct in showing exactly where the product was crashing. So I looked at the function and saw a huge mess of code that was attempting to create a unique name out of the 3dsmax scene object names. It was conflating some custom, do-it-yourself hashing algorithm with some really weird attempts to make unique names on top of that by concatenating names together.

So in attempting to reproduce the crash I created 120 scene objects that all have the same name. Now please understand that 3dsmax couldn’t care less if you named 100,000 scene objects with the same name. It makes no difference since the scene graph is agnostic about the INode names.

But not all 3D file formats are that way, apparently VRML isn’t. Is that perhaps a reason why it’s obsolete?

So once I understood what the VRML exporter wanted, I said to myself: “There are easier ways to generate a hash than this stuff”. The easiest way to get this is to call INode::GetHandle() which returns some sort of unsigned value. I think the value is 32 bits wide (I’m going off of my memory here).

So the easiest way to get a string with the scene node name that is unique is to just print the name and the handle value to a string:

   TSTR buf;
   buf.printf(_T(“%s - %u”), node->GetHandle());

So once that 4 or 5 lines of code replaced the few hundred lines of code, the VRML exporter was now able to export my test scene.

Oh did I mention the cause of the crash in the original code? All those attempts to make a unique name were concatenating the scene node name over and over again to a fixed length stack based buffer that was 256 characters long….

Yes I’m sure you have heard of that problem before…

In a related area, I was testing with a camera that had a name that was way longer than 256 characters. Turns out 3dsmax does NOT support cameras with names longer than 256 characters. Otherwise it crashes somewhere. So I got that fixed too…

So for safety’s sake: Do not attempt to feed strings into 3dsmax that are longer than 256 characters.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s