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?
Well, this -
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
GameDatavalue[id]=strdup(value);
https://en.cppreference.com/w/c/experimental/dynamic/strdup
That seems to be working, running tests!
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:
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.
The free part is returning an error cannot convert parameter 1 from const char* to void *
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*".