AddScriptSection reads past the terminating character.

Started by
3 comments, last by WitchLord 6 years, 10 months ago

This code will produce an error about an unrecognized token after the terminating '\0':


#define SCRIPT(x) #x
static const char kClass[] = SCRIPT(
class Foo
{
    int value;
    Foo()
    {
        value = 0;
    }
});
asIScriptModule *mod = engine->GetModule(0, asGM_ALWAYS_CREATE);
bool r = true;
r &= mod->AddScriptSection("Example", kClass, sizeof(kClass)) >= 0;
r &= mod->Build();
assert(r);
Advertisement
sizeof(kClass) will be the size of the kClass array including the terminating null character, so technically you specifically requested AddScriptSection to read up to and including '\0', which is an unexpected token. You should pass sizeof(kClass) - 1 to the function.

It should still process the \0 as the EOF token, b/c that's standard C though, right? It's not like it's in a language that uses lengths instead of sentinel characters.

Well, it's written in C++, not C, so... it sort of is in such a language, what with std::string storing its length and all. That aside, if a script file I load via this function contains a null character for whatever reason, I'd rather the AngelScript engine reliably produced an error than loaded only part of it. Yes, a typical C string specifically will not contain a null character unless to terminate the string, but nothing else that the AngelScript library interacts with has to act the same, not C++ strings, not file streams, not other languages that AngelScript can be potentially used with. For example, if your application loads script files created by users into an std::string, appends something significant at the end of them and runs that, a user may maliciously create a script that ends with a null character to load their part of the script but avoid loading yours, with unforeseen consequences. A valid script will not contain '\0' but that's exactly why the library has to parse them as well: to be able to report an error when an unexpected '\0' is found.

If there was a compelling reason for accepting the null character as EOF I could easily change the code to do so, but I have to agree with Sir Ementaler on this case. It is better to have the compiler produce an error on unexpected null characters since it is more likely a sign of some error (whether intentionally so, or by some mistake).

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

This topic is closed to new replies.

Advertisement