String literals can be modified with unsafe references.

Started by
2 comments, last by WitchLord 5 months, 3 weeks ago

Hi,

I've been experimenting with AngelScript and I found out that with asEP_ALLOW_UNSAFE_REFERENCES=true you can bind a temporary string to a non const string reference (string&) and modify it. This makes all uses of that string literal change everywhere.

The info function just calls the application's logger, it currently takes a string& and in C++ it passes it to the logger.

void main()
{
    info("String");
    UnsafeRefsAreFun("String");
    info("String");
    Test();
}

void UnsafeRefsAreFun(string& str)
{
    str = "DifferentString";
}

void Test()
{
    info("String");
}

This outputs:

2023-08-14 17:52:23 [info]: String
2023-08-14 17:52:23 [info]: DifferentString
2023-08-14 17:52:23 [info]: DifferentString

It's also possible to use a default parameter to "hide" it.

void UnsafeRefsAreFun(string& str = "")
{
    str = "NotEmptyString";
}

After a call to this function every instance of an empty string literal will be NotEmptyString.

This is only works with unsafe references of course, but I think it's a bit too unsafe and probably isn't intentional(?). It would be nice to get a compiler error if a string literal is bound to a non const string ref. That way only a badly registered interface could change it (in fact that's how I found it!) but that's the same undefined behaviour as casting away the constness of a C++ type.

Advertisement

This does indeed appear to be a miss.

I'll look into it and have it fixed as soon as possible.

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

I've fixed this in revision 2874.

Thanks,
Andreas

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