Game Development Community

Can someone skilled at C++ tell me what I did wrong here?

by Vince Gee · in Torque 3D Professional · 02/16/2012 (9:59 pm) · 3 replies

I'm getting a memory leak, and for the life of me I can't seem to fix it.

The only thing I know is that argc and argv do get destroyed, after the call. But for the life of me I cannot figure out how to make this work.

extern "C" __declspec(dllexport) void ParentCall(
	char * sim_object,
	char* function,
	S32 argc,
	const char** argv,
	char* ret)
{
	SimObject* object = Sim::findObject(sim_object);
	if (!object)
		return;

	char* _function = (char *)malloc(256);  
	dSprintf(_function,256,"%s",function);
	const char* ccfunction = StringTable->insert(_function);

	
    char **mArgv;
	S32  mArgc = argc;
	U32 totalSize = 0;
	S32 i;
	for(i = 0; i < argc; i++)
      totalSize += dStrlen(argv[i]) + 1;
	totalSize += sizeof(char *) * argc;

	mArgv = (char **) dMalloc(totalSize);
	char *argBase = (char *) &mArgv[argc];
	for(i = 0; i < argc; i++)
		{
		mArgv[i] = argBase;
		dStrcpy(mArgv[i], argv[i]);
		argBase += dStrlen(argv[i]) + 1;
		}
	Namespace* ns=	object->getNamespace()->getParent();
	if (!ns)
		return;
	ns->lookup(ccfunction)->execute( mArgc,(const char **)mArgv,&gEvalState);
	//ns->lookup(ccFunction)->
	//dSprintf(ret,1024,"%s",	ns->lookup(ccfunction)->execute( argc,argv,&gEvalState));
}

#1
02/17/2012 (3:29 am)
Looking at just the code you posted, there is memory being allocated on the heap by using "malloc" but it is never being freed with "free".

Check out:

en.wikipedia.org/wiki/C_dynamic_memory_allocation
#2
02/17/2012 (7:22 am)
@Kerry,

Do you see anything wrong with
extern "C" __declspec(dllexport) void ParentCall(
	char* sim_object,
	char* function,
	char* ret,
	S32 argc,
	char ** _argv
	)
{
	SimObject* object = Sim::findObject(sim_object);
	if (!object)
		return;

	Namespace* ns=	object->getNamespace()->getParent();
	if (!ns)
		return;

	std::vector<const char*> arguments;
	for (int i =0;i<argc;i++)
		{
		arguments.push_back(_argv[i]);
		}
	const char** argv = &arguments[0];
	StringTableEntry callMethod = StringTable->insert( function );
	const char* resultstring = ns->lookup(callMethod)->execute( argc,argv, &gEvalState);
	if (dStrlen(resultstring)>0)
		dSprintf(ret,1024,"%s",resultstring);
	else
		dSprintf(ret,1024,"%s","");
	
}
#3
02/17/2012 (9:45 pm)
Not offhand. Are you still getting a memory leak with this function?