I've got the following bit of code, which I've narrowed down to be causing a memory leak (that is, in Task Manager, the Private Working Set of memory increases with the same repeated input string). I understand the concepts of heaps and stacks for memory, as well as the general rules for avoiding memory leaks, but something somewhere is still going wrong:
while(!quit){
char* thebuffer = new char[210];
//checked the function, it isn't creating the leak
int size = FuncToObtainInputTextFromApp(thebuffer); //stored in thebuffer
string bufferstring = thebuffer;
int startlog = bufferstring.find("$");
int endlog = bufferstring.find("&");
string str_text="";
str_text = bufferstring.substr(startlog,endlog-startlog+1);
String^ str_text_m = gcnew String(str_text_m.c_str());
//some work done
delete str_text_m;
delete [] thebuffer;
}
The only thing I can think of is it might be the creation of 'string str_text' since it never goes out of scope since it just reloops in the while? If so, how would I resolve that? Defining it outside the while loop wouldn't solve it since it'd also remain in scope then too. Any help would be greatly appreciated.
You should use scope-bound resource management (also known as RAII), it's good practice in any case. Never allocate memory manually, keep it in an automatically allocated class that will clean up the resource for you in the destructor.
You code might read:
while(!quit)
{
// completely safe, no leaks possible
std::vector<char> thebuffer(210);
int size = FuncToObtainInputTextFromApp(&thebuffer[0]);
// you never used size, this should be better
string bufferstring(thebuffer, size);
// find does not return an int, but a size_t
std::size_t startlog = bufferstring.find("$");
std::size_t endlog = bufferstring.find("&");
// why was this split across two lines?
// there's also no checks to ensure the above find
// calls worked, be careful
string str_text = bufferstring.substr(startlog, endlog - startlog + 1);
// why copy the string into a String? why not construct
// this directly?
String^ str_text_m = gcnew String(str_text_m.c_str());
// ...
// don't really need to do that, I think,
// it's garbage collected for a reason
// delete str_text_m;
}
The point is, you won't get memory leaks if you're ensured your resources are freed by themselves. Maybe the garbage collector is causing your leak detector to mis-fire.
On a side note, your code seems to have lots of unnecessary copying, you might want to rethink how many times you copy the string around. (For example, find "$" and "&" while it's in the vector, and just copy from there into str_text, no need for an intermediate copy.)
Are you #using std, so that str_text's type is std::string? Maybe you meant to write -
String^ str_text_m = gcnew String(str_text.c_str());
(and not gcnew String(str_text_m.c_str()) ) ?
Most importantly, allocating a String (or any object) with gcnew is declaring that you will not be delete'ing it explicitly - you leave it up to the garbage collector. Not sure what happens if you do delete it (technically it's not even a pointer. Definitely does not reference anything on the CRT heap, where new/delete have power).
You can probably safely comment str_text_m's deletion. You can expect gradual memory increase (where the gcnew's accumulate) and sudden decreases (where the garbage collection kicks in) in some intervals.
Even better, you can probably reuse str_text_m, along the lines of -
String^ str_text_m = gcnew String();
while(!quit){
...
str_text_m = String(str_text.c_str());
...
}
I know its recommended to set the freed variable to NULL after deleting it just to prevent any invalid memory reference. May help, may not.
delete [] thebuffer;
thebuffer = NULL; // Clear a to prevent using invalid memory reference
There is a tool called DevPartner which can catch all memory leaks at runtime. If you have the pdb for your application this will give you the line numbers in your application where all memory leak has been observed.
This is best used for really big applications.
Related
In my application's InitInstance function, I have the following code to rewrite the location of the CHM Help Documentation:
CString strHelp = GetProgramPath();
strHelp += _T("MeetSchedAssist.CHM");
free((void*)m_pszHelpFilePath);
m_pszHelpFilePath = _tcsdup(strHelp);
It is all functional but it gives me a code analysis warning:
C26408 Avoid malloc() and free(), prefer the nothrow version of new with delete (r.10).
When you look at the official documentation for m_pszHelpFilePath it does state:
If you assign a value to m_pszHelpFilePath, it must be dynamically allocated on the heap. The CWinApp destructor calls free( ) with this pointer. You many want to use the _tcsdup( ) run-time library function to do the allocating. Also, free the memory associated with the current pointer before assigning a new value.
Is it possible to rewrite this code to avoid the code analysis warning, or must I add a __pragma?
You could (should?) use a smart pointer to wrap your reallocated m_pszHelpFilePath buffer. However, although this is not trivial, it can be accomplished without too much trouble.
First, declare an appropriate std::unique_ptr member in your derived application class:
class MyApp : public CWinApp // Presumably
{
// Add this member...
public:
std::unique_ptr<TCHAR[]> spHelpPath;
// ...
};
Then, you will need to modify the code that constructs and assigns the help path as follows (I've changed your C-style cast to an arguably better C++ cast):
// First three (almost) lines as before ...
CString strHelp = GetProgramPath();
strHelp += _T("MeetSchedAssist.CHM");
free(const_cast<TCHAR *>(m_pszHelpFilePath));
// Next, allocate the shared pointer data and copy the string...
size_t strSize = static_cast<size_t>(strHelp.GetLength() + 1);
spHelpPath std::make_unique<TCHAR[]>(strSize);
_tcscpy_s(spHelpPath.get(), strHelp.GetString()); // Use the "_s" 'safe' version!
// Now, we can use the embedded raw pointer for m_pszHelpFilePath ...
m_pszHelpFilePath = spHelpPath.get();
So far, so good. The data allocated in the smart pointer will be automatically freed when your application object is destroyed, and the code analysis warnings should disappear. However, there is one last modification we need to make, to prevent the MFC framework from attempting to free our assigned m_pszHelpFilePath pointer. This can be done by setting that to nullptr in the MyApp class override of ExitInstance:
int MyApp::ExitInstance()
{
// <your other exit-time code>
m_pszHelpFilePath = nullptr;
return CWinApp::ExitInstance(); // Call base class
}
However, this may seem like much ado about nothing and, as others have said, you may be justified in simply supressing the warning.
Technically, you can take advantage of the fact that new / delete map to usual malloc/free by default in Visual C++, and just go ahead and replace. The portability won't suffer much as MFC is not portable anyway. Sure you can use unique_ptr<TCHAR[]> instead of direct new / delete, like this:
CString strHelp = GetProgramPath();
strHelp += _T("MeetSchedAssist.CHM");
std::unique_ptr<TCHAR[]> str_old(m_pszHelpFilePath);
auto str_new = std::make_unique<TCHAR[]>(strHelp.GetLength() + 1);
_tcscpy_s(str_new.get(), strHelp.GetLength() + 1, strHelp.GetString());
m_pszHelpFilePath = str_new.release();
str_old.reset();
For robustness for replaced new operator, and for least surprise principle, you should keep free / strdup.
If you replace multiple of those CWinApp strings, suggest writing a function for them, so that there's a single place with free / strdup with suppressed warnings.
sorry for avoiding you guys
i have a problem with reverse function in circular linked list.
void reverse() {
int num = many;
node* current = head;
node* previous = 0;
while (num != 0) {
cout << "1" << '\t';
node* r = previous;
previous = current;
current = current->next;
previous->next = r;
num--;
}
head = previous;
}
in this func after 2 while sentence
problem comes up in line that current = current->next;
(exception throw : read access violation,
current was 0xDDDDDDDD)
how to handle it??
This is from Visual Studio trying to help you (and succeeding, IMO).
As Mark Ingraham pointed out in another answer a long time ago, Visual Studio's runtime library will fill a block of data with 0xDDDDDDDD when you release a block of heap memory.
So, although you haven't shown any code that's deleting from your list, if there is such code, that's probably the first place to look--at least at first glance, it looks like there's a fair chance that when you try erase a node from the list, you're deleting the memory the node lives in, but still leaving a pointer to that deleted memory.
It's also possible (but less likely, IMO) that you're just using memory without initializing it--and you happen to be hitting a block of memory that was previously allocated and then released back to the heap manager.
The bottom line, however, is that you don't "handle" the access violation. Instead, you need to find the bug in your code that's leading to the access violation happening, and fix it so that doesn't happen any more.
I have 2 code like this
Code 1: CString::Format method
CString cStr;
char* ToString(CString pszFormat, ...)
{
va_list argList;
va_start(argList, pszFormat);
cStr.FormatV(_T(pszFormat), argList);
va_end(argList);
return (LPTSTR)(LPCTSTR)cStr;
//Note that this will return the pointer to the cstring content
}
Code 2: sprintf_s method
char strChar[100];
char* ToString(char const* const _Format, ...)
{
va_list argList;
va_start(argList, _Format);
vsprintf_s(strChar, _Format, argList);
va_end(argList);
return strChar;
//Note that this will return the pointer to the string content
}
In code 1, I feel totally safe - I don't have to afraid about the length maybe too long. But I'm afraid that code 1 may reduce the performance. I don't know if it may cause memory leak or not. And I think that if Cstring has dynamic length, maybe it will allocate and free memory like no one business.
So I come up with code 2. But in code 2, I face the risk if I pass the _Format too long - like string that has length as 1000 - then the program will crash with 'buffer too small' error.
I don't know which one is better: CString::Format or sprintf_s ??? If sprintf_s really increase performance and CString::Format is bad for performance, then I'll take more effort to prevent 'buffer too small' in sprintf_s. But if sprintf_s not worth it - I'll take CString::Format.
Thank for reading.
If you are worried that the buffer in strChar might overflow, then why not simply use vsnprintf_s(). The second argument will restrict the number of characters written to the output buffer. You can modify your 'ToString()' function to receive this extra sizeOfBuffer field and pass it on to vsnprintf_s().
See [https://msdn.microsoft.com/en-us/library/d3xd30zz.aspx][1] for the details and other ways to prevent a buffer overrun.
I am using C++/CLI and I want to call the function WNetAddConnection2 from Windows Networking.
First, I know that C++/CLI is not the language of choice for my work, but I have no possibility to change that right now and e.g. use C# instead.
The problem now is, that this function takes wchar_t*, so I need to convert System::String^ to wchar_t*.
Solution 1): use pin_ptr and PtrToSTringChars from vcclr.h
Solution 2): use StringToHGlobalUni. (The title mentions StringHToGlobalAnsi because more people are searching for that so they might find this post and it's answers faster).
I have found out that both solutions work. But #1 does not really. I have put the WNet-functions into a ref class CWNetShare with following constructor:
CWNetShare::CWNetShare (String^ i_sLocalDrive, ...) {
pin_ptr<const wchar_t> wszTemp;
wszTemp = PtrToStringChars(i_sLocalDrive);
m_wszLocalDrive = const_cast<wchar_t*>(wszTemp);
where m_wszLocalDrive is a private CWNetShare member of type wchar_t*.
The real problem: while calling the constructor by m_oWNetShare = gcnew CWNetShare from a Winform class constructor (I know, C++/CLI and Winforms...), everything seems fine. The string i_sLocalDrive and others are converted and assigned correctly. But when accessing m_oWNetShare later, the values in all m_wsz... variables are lost. It looks like the object was moved around by the GC.
Therefore I have made a test:
ref class CManaged {
public:
wchar_t* m_wszNothing;
wchar_t* m_wszPinned;
wchar_t* m_wszMarshal;
System::String^ m_sTest;
CManaged ()
{
m_sTest = "Hello";
m_wszNothing = L"Test";
pin_ptr<const wchar_t> wszTemp;
wszTemp = PtrToStringChars(m_sTest);
m_wszPinned = const_cast<wchar_t*>(wszTemp);
m_wszMarshal = static_cast<wchar_t*>(System::Runtime::InteropServices::Marshal::StringToHGlobalUni (m_sTest).ToPointer());
}
};
Again a winform with m_oManaged = gcnew CManaged; in its constructor. When accessing m_oManaged later, then if m_oManaged was not moved, m_wszPinned is ok.
But after GCing, it's showing nonsense. BUT m_wsznothing keeps it's value, so it's not a problem of wchar_t*, but of the pin_ptr somehow. The address of m_oManaged has changed, but the address of m_wszPinned is the same, so why is the value lost then?
What is going wrong here?
Does pin_ptr and PtrToSTringChars have a use at all then?
I'm using marshalling now, which works.
PtrToStringChars is literally that: a pointer to the character array that the String^ holds internally.
When you're saving that pointer, it's a pointer to a managed object that the garbage collector is allowed to move. You're only guaranteed that it won't move for as long as the pin_ptr exists, which you're not keeping around. As soon as the pin_ptr no longer exists, the garbage collector is free to move the managed object around, and your pointer now points at some other object, somewhere in the managed heap.
Use PtrToStringChars if you're going to call an unmanaged function, and you don't need the string to persist beyond that one API call (and the unmanaged function doesn't keep a reference to the string). Use StringToHGlobalUni if you need to keep the unmanaged string around long-term.
char* XX (char* str)
{
// CONCAT an existing string with str , and return to user
}
And i call this program by:
XX ( strdup("CHCHCH") );
Will this cause a leak while not releasing what strdup() generates ?
It's unlikely that free the result of XX() will do the job.
(Please let me know both in C and C++ , thanks !)
Unless the XX function free()'s the argument passed in, yes this will cause a memory leak in both C and C++.
Yes. Something has to free the result of strdup.
You could consider using Boehm's garbage collector and use GC_strdup & GC_malloc instead of strdup & malloc; then you don't need to bother about calling free
Yes this will leak. strdup's results must be freed.
For C++, on the other hand, I recommend using std::string rather than char*:
std::string XX( std::string const & in )
{
return in + std::string( "Something to append" );
}
This is a quick-and dirty way to implement what you're talking about, but it is very readable. You can obtain some speed improvement by passing in a mutable reference to a string for output, but unless this is in a very tight loop, there is little reason to do so, as it would likely add increased complication without booting performance significantly.