0

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

2
Contributors
6
Replies
7
Views
6 Years
Discussion Span
Last Post by Caligulaminus
0

How about

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

?

sorry ...but it didn't work

0

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

0

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;
		}
 
	}
}
0

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.