Adventure Game Studio

AGS Support => Advanced Technical Forum => Topic started by: Dualnames on Mon 01/04/2019 20:40:47

Title: PLUGIN String issue (I think)
Post by: Dualnames on Mon 01/04/2019 20:40:47
So I have this code in my plugin:


const char*GameDatavalue[40000];

void SaveVariable(const char*value,int id)
{
GameDatavalue[id]=value;
}

const char* ReadVariable(int id)
{
if (GameDatavalue[id]==NULL)
{
return engine->CreateScriptString("");
}
else
{
return engine->CreateScriptString(GameDatavalue[id]);
}
}


Unfortunately a lot of the times when I'm calling ReadVariable in a simple way, like tryin to read the value, I get weird returns like symbols @ __ and definitely a wrong string. This time I triple checked, and I'm confident the issue lies on the plugin side of things, pasted above. Any thoughts why it faulters?
Title: Re: PLUGIN String issue (I think)
Post by: Crimson Wizard on Mon 01/04/2019 20:45:25
Well, this -
Code (cpp) Select

const char*GameDatavalue[40000];
void SaveVariable(const char*value,int id)
{
GameDatavalue[id]=value;
}


looks potentially dangerous, because you don't copy string value, but assign a pointer. If anything happens to the former string (got deleted or overwritten) your value will become screwed.

If you are using strictly C strings, I'd suggest doing
Code (cpp) Select

GameDatavalue[id]=strdup(value);

https://en.cppreference.com/w/c/experimental/dynamic/strdup
Title: Re: PLUGIN String issue (I think)
Post by: Dualnames on Mon 01/04/2019 20:48:43
That seems to be working, running tests!
Title: Re: PLUGIN String issue (I think)
Post by: Crimson Wizard on Mon 01/04/2019 20:52:51
Oh, I forgot to mention, in this case you'd also need to call free() to remove previous string, and maybe on plugin exit too:

Code (cpp) Select

void SaveVariable(const char*value,int id)
{
        if (GameDatavalue[id] != NULL)
            free(GameDatavalue[id]);

        if (value != null)
            GameDatavalue[id]=strdup(value);
        else
            GameDatavalue[id]=NULL;
}

otherwise there will be memory leaks and you run out of memory after a while.

But really, if you don't need them to be strictly C strings, perhaps just use std::vector<std::string>, that will save you from lots of trouble.
Title: Re: PLUGIN String issue (I think)
Post by: Dualnames on Mon 01/04/2019 22:17:07
The free part is returning an error cannot convert parameter 1 from const char* to void *
Title: Re: PLUGIN String issue (I think)
Post by: Crimson Wizard on Mon 01/04/2019 22:19:44
Quote from: Dualnames on Mon 01/04/2019 22:17:07
The free part is returning an error cannot convert parameter 1 from const char* to void *

Oh right, since you are creating new strings, then GameDatavalue must be "char*" instead of "const char*".