Re: Memory leaks help with char*
- From: David Wilkinson <no-reply@xxxxxxxxxxxx>
- Date: Fri, 14 Oct 2005 21:16:44 -0400
Jeremy Chapman wrote:
I've written the following code. After not having written a single line of c++ for about 3 or more years, I'm feeling a little uneasy about it.
First of all, I'm sure I've got some memory leaks here. Also, I get an error when I try to delete my char* variables. I've tried delete and delete[].
Can someone verify I'm doing this right?
//Get appdirectory char* pszFileName = new char[1024]; pszFileName[1024] = 0;
char* pszCommand = new char[1024]; pszCommand[1024] = 0;
char* pszArgs = new char[1024]; pszArgs[1024] = 0;
DWORD nSize = 1024; DWORD iRetVal = GetModuleFileName(NULL,pszFileName,nSize);
//Load config file for this app pszFileName = strcat(pszFileName,".config"); ifstream pfile(pszFileName, ios::in|ios::binary);
if (pfile) { //first line in app is command to run pfile.getline(pszCommand, 1024); //second line is parameters pfile.getline(pszArgs, 1024);
pfile.close(); //delete pfile; }
ShellExecute(NULL, pszCommand, pszArgs, NULL, NULL, SW_SHOWNORMAL);
return 0;
Jeremy:
In addition to Barry's comment (you don't need that line anyway), never use "new" unless you have to. Just do
char pszFileName[_MAX_PATH+10];
This leaves room for the ".config" that you want to add.
You could do also
char pszCommand[1024]; char pszArgs[1024];
but you would do better to do
std::string command; std::string args;
std::getline(pFile, command); std::getline(pFile, args);
ShellExecute(NULL, command.c_str(), args.c_str(), NULL, NULL, SW_SHOWNORMAL);
Are you sure that this code is going to work? GetModuleFileName() gets the full path of the executable, which probably has a .exe extension.
Your code will certainly leak as written. Every time you use new, there must be a corresponding delete or delete []. Here you need delete []. Don't know why this did not work for you. But you don't need those new's anyway.
HTH,
David Wilkinson
.
- Follow-Ups:
- Re: Memory leaks help with char*
- From: Jeremy Chapman
- Re: Memory leaks help with char*
- References:
- Memory leaks help with char*
- From: Jeremy Chapman
- Memory leaks help with char*
- Prev by Date: Re: Memory leaks help with char*
- Next by Date: Re: Template compilation problem
- Previous by thread: Re: Memory leaks help with char*
- Next by thread: Re: Memory leaks help with char*
- Index(es):
Relevant Pages
|