PLUGIN String issue (I think)

Started by Dualnames, Mon 01/04/2019 20:40:47

Previous topic - Next topic

Dualnames

So I have this code in my plugin:

Code: ags

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?
Worked on Strangeland, Primordia, Hob's Barrow, The Cat Lady, Mage's Initiation, Until I Have You, Downfall, Hunie Pop, and every game in the Wadjet Eye Games catalogue (porting)

Crimson Wizard

#1
Well, this -
Code: cpp

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

GameDatavalue[id]=strdup(value);

https://en.cppreference.com/w/c/experimental/dynamic/strdup

Dualnames

That seems to be working, running tests!
Worked on Strangeland, Primordia, Hob's Barrow, The Cat Lady, Mage's Initiation, Until I Have You, Downfall, Hunie Pop, and every game in the Wadjet Eye Games catalogue (porting)

Crimson Wizard

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

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.

Dualnames

The free part is returning an error cannot convert parameter 1 from const char* to void *
Worked on Strangeland, Primordia, Hob's Barrow, The Cat Lady, Mage's Initiation, Until I Have You, Downfall, Hunie Pop, and every game in the Wadjet Eye Games catalogue (porting)

Crimson Wizard

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*".

SMF spam blocked by CleanTalk