Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

memory management???

Status
Not open for further replies.

computerwhiz

Programmer
May 1, 2002
28
US
Is there a faster way to insert a particular string into a string at a certain position? Here is the code I am using now. <pszText> is a static global variable accessed in several functions. My program is running to slow, would reallocation be faster than what I am doing now?


Code:
void Insert(int iLen, LPSTR String)
{
  if (iLen < 0 || iLen > lstrlen(pszText) || String == 0X00)
  {
    return;
  }
  LPSTR NewText = (LPSTR)GlobalAlloc(GPTR,
    lstrlen(String)+ lstrlen(pszText) + 2);
  if (iLen > 0)
  {
    CopyMemory(NewText, pszText, iLen);
  }
  CopyMemory(NewText+iLen, String, lstrlen(String));
  if (lstrlen(pszText)-iLen > 0)
  {
    CopyMemory(NewText+iLen+lstrlen(String), pszText+iLen,
      lstrlen(pszText)-iLen);
  }
  GlobalFree(pszText);
  pszText = (LPSTR)GlobalAlloc(GPTR, lstrlen(NewText) + 2);
  lstrcpy(pszText, NewText);
  pszText[lstrlen(NewText)+1] = 0x00;
  GlobalFree(NewText);
}
 
There are all sorts of ways of managing memory which are better than what you're doing.
You move the whole file in effect every time you edit the text.

Start with say
Code:
int max_lines = 10000;
char **lines = new char *[max_lines];
If you end up with more than 10K lines, then extend accordingly.

Moving a line then becomes as simple as
Code:
lines[i] = lines[i+1];

--
 
I would recommend reallocation and then just adding the new string into the correct position, i think its a bit quicker and simpler than your current method.

But as salem suggests, it would be better to start with a "pool" of memory available, then only re-alloc when you are out of mem

Skute

&quot;There are 10 types of people in this World, those that understand binary, and those that don't!&quot;
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top