Can any body suggest me how can I free the dynamic memory in the given code

int fun(CString qry, CStringList *List,int n)
{
    using namespace std;
	string sqlStmt = qry;
	int i;
	this->stmt = this->conn->createStatement (sqlStmt);
	ResultSet *rset = this->stmt->executeQuery ();
	string **oraRecordsStr=NULL;
	try 
	{	
		while (rset->next())
		{
			if(oraRecordsStr == NULL)
			{
				oraRecordsStr=new string*[n];
				for(i=0;i<n;i++)
					oraRecordsStr[i] = new string;
			}
		
			for(i=0;i<n;i++)
			{
				*oraRecordsStr[i]= rset->getString (i+1);
				List->AddTail(oraRecordsStr[i]->c_str());
			}

			for(i=0;i<n;i++)
				oraRecordsStr[i] = NULL;

			oraRecordsStr=NULL;
		}
		
	}
}

i tried

for(i=0;i<n;i++)
       delete []oraRecordsStr[i];
       delete []oraRecordsStr;

but it didn't work

Thanks in advance

How about

for(i=0;i<n;i++)
    delete oraRecordsStr[i];
delete [] oraRecordsStr;

?

How about

for(i=0;i<n;i++)
    delete oraRecordsStr[i];
delete [] oraRecordsStr;

?

sorry ...but it didn't work

Well, "didn't work" is not very meaningful.

Btw.: In lines 26-29 you set all pointers to NULL. That will of course make it impossible to delete them anymore.

Well, "didn't work" is not very meaningful.

Caligulaminus you rock!!!
Your solution worked like a charm.I misplaced the code you gave previously.But after replacing the code with highlighted lines it worked absolutely fine. If you could explain why it was not working previously i.e. the code in my original post, I will be highly thankful.

int fun(CString qry, CStringList *List,int n)
{
    using namespace std;
	string sqlStmt = qry;
	int i;
	this->stmt = this->conn->createStatement (sqlStmt);
	ResultSet *rset = this->stmt->executeQuery ();
	string **oraRecordsStr=NULL;
	try 
	{	
		while (rset->next())
		{
			if(oraRecordsStr == NULL)
			{
				oraRecordsStr=new string*[n];
				for(i=0;i<n;i++)
					oraRecordsStr[i] = new string;
			}
 
			for(i=0;i<n;i++)
			{
				*oraRecordsStr[i]= rset->getString (i+1);
				List->AddTail(oraRecordsStr[i]->c_str());
			}
 
			for(i=0;i<n;i++)
			delete oraRecordsStr[i];
			delete [] oraRecordsStr;
			oraRecordsStr=NULL;
		}
 
	}
}

You must use delete [] only for new type[]. But you trieed to use it to free each individual string.

delete []oraRecordsStr[i]; // <- wrong

And you must not set the pointer to NULL before deleting it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.