Memory failures when calling new - c++

It might be a little hard to explain everything about this error but I'll try my best. Unfortunately the code is so large that it would be unpractical to try to include it.
I am writing an academic OS for homework (nachos if you must know) and the most recent thing I needed to do was implement mutual exclusion in a core map. To do this I added a Lock and a condition variable per page in emulated main memory. After doing this I run my code and get through one call to the exception (in a completely different directory from core map) handler just fine, but the second time the function gets called I get and error on the following call: r=new Lock("read"); and it reads like this:
*** glibc detected *** /home/some_other_directories/workspace/nachos3_repo/vm/nachos: malloc(): memory corruption (fast): 0x0805fe20 ***
Just to see how it behaves I changed the allocation of that lock to be an extern in my system file (there are a lot of global externs there) and after that I get a seg fault on the call fout.open("old.txt"); which I traced back through the stack to be within a call to malloc in a call to new.
My best guess is that my heap is getting to large but I am not sure if that is the case or how to handle it if it is. can anyone shed light on this problem?

malloc is just the victim here. In some completely different part of the code you have written outside the allocated boundaries and thus have corrupted chain links that are used by the heap manager to track free/allocated blocks. As you try to allocate here, the heap manager is chasing these linked lists and lands into a protected area (most likely not allocated). You should do a review of your changes first and see if you can spot where you scribble the memory.

Related

How to find reason for app crash on close?

My Qt5 app crashes when I hit the close window returning:
MyApp(28741,0x7fff7aa73000) malloc: *** error for object 0x7fc40bc8e300: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
The program has unexpectedly finished.
Classic approach to recover it, I guess, is to disable application modules (should I say parts of it, when things are not so well organized) systematically until the problem appears.
Is there some (more) intelligent way to solve this issue?
From what has been returned the problem is obvious, there is pointer somewhere being deleted (at least) two times. But were is this thing hiding?
What can I do with 28741,0x7fff7aa73000? And with 0x7fc40bc8e300? Can I use those to find something in Qt Creator 4 on Mac?
Because the app crash on close it means the problem is in a destructor?
From what has been returned the problem is obvious, there is pointer somewhere being deleted (at least) two times. But were is this thing hiding?
Not exactly; what you say is normally signaled as a "double free"; this seems more like somebody is passing to free something that never came from malloc.
To pinpoint it, do as the message says:
*** set a breakpoint in malloc_error_break to debug.
(or really, even just run it under a debugger; normally on Linux it does break into the debugger at the top of the stack when the program is aborted)
Once the breakpoint is hit, walk up the call stack and see what pointer is being freed, and try to find out why it is being freed when it doesn't actually come from malloc.
The fact that the address is "big" (0x7fc40bc8e300) tells that it probably comes from the stack (if OS X is anything like Linux, the heap is "down" in memory, the stack is at the opposite side of the virtual address space), so probably it's just as simple as somebody passing to free or delete an address that comes from the stack. This often happens when you erroneously pass a stack-allocated object to some method that wants to take ownership of it and free it with free or delete when it isn't needed anymore.
Also, running valgrind never hurts, but I doubt that in this case it can be of any help - you don't seem to be dealing with an invalid pointer (which it would detect at the first read/write), but you have a valid non-heap-allocated pointer that is being incorrectly deallocated with free. It will probably detect it at the same time as free itself.

C++ - Debug Assertion Failed on program exit

When calling 'exit', or letting my program end itself, it causes a debug assertion:
.
Pressing 'retry' doesn't help me find the source of the problem. I know that it's most likely caused by memory being freed twice somewhere, the problem is that I have no clue where.
The whole program consists of several hundred thousand lines which makes it fairly difficult to take a guess on what exactly is causing the error. Is there a way to accurately tell where the source of the problem is located without having to comb line for line through the code?
The callstack doesn't really help either:
.
this kind of errors usally appear if you delete already deleted objects.
this happens if one object is given to multiple other objects that are supposed to take ownership of that first object and both try to delete it in their destructor.
As the messagebox already suggests, you're probably corrupting your heap in some way. Either you free/delete some memory block that you should not or you're trying to write to some memory block that has already been freed/deleted.
The callstack suggests that this is probably happening when stepping over the last line of your main function. If that is the case, then the problem is probably in the cleanup routines of some user defined types of which you create instances inside the main function. Try setting breakpoints inside the destructors of your own classes and investigate.
It is possible that you are corrupting the heap during the program operation, but it is not being detected until the end of the program, in which case the stack trace would only point to the memory checking routine
There may be a function you can call during operation that checks if the heap is valid, which may bring the fail closer to the point of corruption
HeapValidate is an example of such a routine, but it would depend on what platform you are using
This error can also happen when you use delete[] instead of delete. However, as mentioned, this is only one of many causes.

I get an exception if I leave the program running for a while

Platform : Win32
Language : C++
I get an error if I leave the program running for a while (~10 min).
Unhandled exception at 0x10003fe2 in ImportTest.exe: 0xC0000005: Access violation reading location 0x003b1000.
I think it could be a memory leak but I don't know how to find that out.
Im also unable to 'free()' memory because it always causes (maybe i shouldn't be using free() on variables) :
Unhandled exception at 0x76e81f70 in ImportTest.exe: 0xC0000005: Access violation reading location 0x0fffffff.
at that stage the program isn't doing anything and it is just waiting for user input
dllHandle = LoadLibrary(L"miniFMOD.dll");
playSongPtr = (playSongT)GetProcAddress(dllHandle,"SongPlay");
loadSongPtr = (loadSongT)GetProcAddress(dllHandle,"SongLoadFromFile");
int songHandle = loadSongPtr("FILE_PATH");
// ... {just output , couldn't cause errors}
playSongPtr(songHandle);
getch(); // that is where it causes an error if i leave it running for a while
Edit 2:
playSongPtr(); causes the problem. but i don't know how to fix it
I think it's pretty clear that your program has a bug. If you don't know where to start looking, a useful technique is "divide and conquer".
Start with your program in a state where you can cause the exception to happen. Eliminate half your code, and try again. If the exception still happens, then you've got half as much code to look through. If the exception doesn't happen, then it might have been related to the code you just removed.
Repeat the above until you isolate the problem.
Update: You say "at that stage the program isn't doing anything" but clearly it is doing something (otherwise it wouldn't crash). Is your program a console mode program? If so, what function are you using to wait for user input? If not, then is it a GUI mode program? Have you opened a dialog box and are waiting for something to happen? Have you got any Windows timers running? Any threads?
Update 2: In light of the small snippet of code you posted, I'm pretty sure that if you try to remove the call to the playSongPtr(songHandle) function, then your problem is likely to go away. You will have to investigate what the requirements are for "miniFMOD.dll". For example, that DLL might assume that it's running in a GUI environment instead of a console program, and may do things that don't necessarily work in console mode. Also, in order to do anything in the background (including playing a song), that DLL probably needs to create a thread to periodically load the next bit of the song and queue it in the play buffer. You can check the number of threads being created by your program in Task Manager (or better, Process Explorer). If it's more than one, then there are other things going on that you aren't directly controlling.
The error tells you that memory is accessed which you have not allocated at the moment. It could be a pointer error like dereferencing NULL. Another possibility is that you use memory after you freed it.
The first step would be to check your code for NULL reference checks, i.e. make sure you have a valid pointer before you use it, and to check the lifecycle of all allocated and freed resources. Writing NULL's over references you just freed might help find the problem spot.
I doubt this particular problem is a memory leak; the problem is dereferencing a pointer that does not point to something useful. To check for a memory leak, watch your process in your operating system's process list tool (task manager, ps, whatever) and see if the "used memory" value keeps growing.
On calling free: You should call free() once and only once on the non-null values returned from malloc(), calloc() or strdup(). Calling free() less than once will lead to a memory leak. Calling free() more than once will lead to memory corruption.
You should get a stack trace to see what is going on when the process crashes. Based on my reading of the addresses involved you probably have a stack overflow or have an incorrect pointer calculation using a stack address (in C/C++ terms: an "auto" variable.) A stack trace will tell you how you got to the point where it crashed.

What can cause "corrupted double-linked list" error?

I am having problems with a fairly complex code. I wasn't able to produce a short snippet that reproduces the error, so I'll try to explain the problem in words.
The code crashes randomly with the error
*** glibc detected *** gravtree: corrupted double-linked list: 0x000000001aa0fc50 ***
Debugging showed that it comes from the line where the codes frees an object. There seems to be nothing wrong with the object. It exists, and I can access it's data at the time the error occurs. The object's destructor is trivial and doesn't do anything.
So, I'm kind of stuck. In what kind of circumstances do you expect 'free' to fail?
Try running your program under Valgrind. It may point you to an earlier cause, whereas gdb is only breaking in where damage has already occurred.
As Warren said, Valgrind is usually the best way to find it. The doubly linked list is a base of usually network or binary data handlers, ie in QT QByteArray or QTcpSocket. I had the same thing today and it was because I had invalidated an object by deleting it off a map but had previously obtained pointers to data inside of it. It worked sometimes, sometimes not. The higher the load on the system the more likely it would crash.

Debugging a memory error with GDB and C++

I'm running my C++ program in gdb. I'm not real experienced with gdb, but I'm getting messages like:
warning: HEAP[test.exe]:
warning: Heap block at 064EA560 modified at 064EA569 past requested size of 1
How can I track down where this is happening at? Viewing the memory doesn't give me any clues.
Thanks!
So you're busting your heap. Here's a nice GDB tutorial to keep in mind.
My normal practice is to set a break in known good part of the code. Once it gets there step through until you error out. Normally you can determine the problem that way.
Because you're getting a heap error I'd assume it has to do with something you're putting on the heap so pay special attention to variables (I think you can use print in GDB to determine it's memory address and that may be able to sync you with where your erroring out). You should also remember that entering functions and returning from functions play with the heap so they may be where your problem lies (especially if you messed your heap before returning from a function).
You can probably use a feature called a "watch point". This is like a break point but the debugger stops when the memory is modified.
I gave a rough idea on how to use this in an answer to a different question.
If you can use other tools, I highly recommend trying out Valgrind. It is an instrumentation framework, that can run your code in a manner that allows it to, typically, stop at the exact instruction that causes the error. Heap errors are usually easy to find, this way.
One thing you can try, as this is the same sort of thing as the standard libc, with the MALLOC_CHECK_ envronment variable configured (man libc).
If you keep from exiting gdb (if your application quit's, just use "r" to re-run it), you can setup a memory breakpoint at that address, "hbreak 0x64EA569", also use "help hbreak" to configure condition's or other breakpoitn enable/disable options to prevent excessively entering that breakpoint....
You can just configure a log file, set log ... setup a stack trace on every break, "display/bt -4", then hit r, and just hold down the enter key and let it scroll by
"or use c ## to continue x times... etc..", eventually you will see that same assertion, then you will now have (due to the display/bt) a stacktrace which you can corolate to what code was modifying on that address...
I had similar problem when I was trying to realloc array of pointers to my structures, but instead I was reallocating as array of ints (because I got the code from tutorial and forgot to change it). The compiler wasnt correcting me because it cannot be checked whats in size argument.
My variable was:
itemsetList_t ** iteration_isets;
So in realloc instead of having:
iteration_isets = realloc(iteration_isets, sizeof(itemsetList_t *) * max_elem);
I had:
iteration_isets = realloc(iteration_isets, sizeof(int) * max_elem);
And this caused my heap problem.