malloc causes the application to crash and show memory map [duplicate] - c

I have a large body of legacy code that I inherited. It has worked fine until now. Suddenly at a customer trial that I cannot reproduce inhouse, it crashes in malloc. I think that I need to add instrumentation e.g on top of malloc I have my own malloc that stores some meta information about each malloc e.g. who has made the malloc call. When it crashes, I can then look up the meta information and see what was happening. I had done something similar years ago but cannot recall it now...I am sure people have come up with better ideas. Will be glad to have inputs.
Thanks

Is memory allocation broken?
Try valgrind.
Malloc is still crashing.
Okay, I'm going to have to assume that you mean SIGSEGV (segmentation fault) is firing in malloc. This is usually caused by heap corruption. Heap corruption, that itself does not cause a segmentation fault, is usually the result of an array access outside of the array's bounds. This is usually nowhere near the point where you call malloc.
malloc stores a small header of information "in front of" the memory block that it returns to you. This information usually contains the size of the block and a pointer to the next block. Needless to say, changing either of these will cause problems. Usually, the next-block pointer is changed to an invalid address, and the next time malloc is called, it eventually dereferences the bad pointer and segmentation faults. Or it doesn't and starts interpreting random memory as part of the heap. Eventually its luck runs out.
Note that free can have the same thing happen, if the block being released or the free block list is messed up.
How you catch this kind of error depends entirely on how you access the memory that malloc returns. A malloc of a single struct usually isn't a problem; it's malloc of arrays that usually gets you. Using a negative (-1 or -2) index will usually give you the block header for your current block, and indexing past the array end can give you the header of the next block. Both are valid memory locations, so there will be no segmentation fault.
So the first thing to try is range checking. You mention that this appeared at the customer's site; maybe it's because the data set they are working with is much larger, or that the input data is corrupt (e.g. it says to allocate 100 elements and then initializes 101), or they are performing things in a different order (which hides the bug in your in-house testing), or doing something you haven't tested. It's hard to say without more specifics. You should consider writing something to sanity check your input data.

Try Asan
AddressSanitizer (aka ASan) is a memory error detector for C/C++. It finds:
Use after free (dangling pointer dereference)
Heap buffer overflow
Stack buffer overflow
Global buffer overflow
Use after return
Use after scope
Initialization order bugs
Memory leaks
Please find the links to know more and how to use it
https://github.com/google/sanitizers/wiki/AddressSanitizer and
https://github.com/google/sanitizers/wiki/AddressSanitizerFlags

I know this is old, but issues like this will continue to exist as long as we have pointers. Although valgrind is the best tool for this purpose, it has a steep learning curve and often the results are too intimidating to understand.
Assuming you are working on some *nux, another tool I can suggest is electricfence. Quote:
Electric Fence helps you detect two common programming bugs:
software that overruns the boundaries of a malloc() memory allocation,
software that touches a memory allocation that has been released by free().
Unlike other malloc() debuggers, Electric Fence will detect read accesses
as well as writes, and it will pinpoint the exact instruction that causes
an error.
Usage is amazingly simple. Just link your code with an additional library lefence
When you run the application, a corefile will be generated when memory is corrupted, instead of when corrupted memory is used.

Related

Debugging memory leak issues without any tool

Interviewer - If you have no tools to check how would you detect memory leak problems?
Answer - I will read the code and see if all the memory I have allocated has been freed by me in the code itself.
Interviewer wasn't satisfied. Is there any other way to do so?
For all the implementation defined below, one needs to write wrappers for malloc() & free() functions.
To keep things simple, keep track of count of malloc() & free(). If not equal then you have a memory leak.
A better version would be to keep track of the addresses malloc()'ed & free()'ed this way you can identify which addresses are malloc()'ed but not free()'ed. But this again, won't help much either, since you can't relate the addresses to source code, especially it becomes a challenge when you have a large source code.
So here, you can add one more feature to it. For eg, I wrote a similar tool for FreeBSD Kernel, you can modify the malloc() call to store the module/file information (give each module/file a no, you can #define it in some header), the stack trace of the function calls leading to this malloc() and store it in a data structure, along side the above information whenever a malloc() or free() is called. Use addresses returned by malloc() to match with it free(). So, when their's a memory leak, you have information about what addresses were not free()'ed in which file, what were the exact functions called (through the stack trace) to pin point it.
The way, this tool worked was, on a crash, I used to get a core-dump. I had defined globals (this data structure where I was collecting data) in kernel memory space, which I could access using gdb and retrieve the information.
Edit:
Recently while debugging a memeory leak in linux kernel, I came across this tool called kmemleak which implements a similar algorithm I described in point#3 above. Read under the Basic Algorithm section here: https://www.kernel.org/doc/Documentation/kmemleak.txt
My response when I had to do this for real was to build tools... a debugging heap layer, wrapped around the C heap, and macros to switch code to running against those calls rather than accessing the normal heap library directly. That layer included some fencepost logic to detect array bounds violations, some instrumentation to monitor what the heap was doing, optionally some recordkeeping of exactly who allocated and freed each block...
Another approach, of course, is "divide and conquer". Build unit tests to try to narrow down which operations are causing the leak, then to subdivide that code further.
Depending on what "no tools" means, core dumps are also sometimes useful; seeing the content of the heap may tell you what's being leaked, for example.
And so on....

What does it mean when malloc() or free() gives you a segmentation fault?

I am currently using dlmalloc() to see how much faster it can be than the original libc malloc().
However, running free() keeps giving me a segmentation fault...
Does anyone know some logical reasons why this could keep happening?
A segfault inside the memory management functions almost always indicates that you've done something wrong (like overwriting memory beyond the valid bounds) before the call that actually segfaults.
Running your code under Valgrind may help you determine the real source of the problem.
I would be looking first into memory corruption issues. For example, if you allocate N bytes and then write to N+100 of them, you're very likely to corrupt the memory arena.
That's because many implementations keep their housekeeping information (block sizes, list pointers and so on) in-line (between the actual data areas).
Another possibility would be double freeing of blocks which may cause problems if that memory has since been used for some other allocation (especially if your address is now in the middle of a data area rather than at the beginning).
First things first, make sure you're following the rules. Any thing else is undefined behaviour and all bets are off.
You may also want to post the source code for the problem you're having so we can examine it. If you do this, try to reduce it to the smallest example that exhibits the problem. Only the most dedicated SOer (a) will want to look over some 10,000-line behemoth to find your issue .
(a) And I'm certainly not that dedicated :-)

Checking for memory leaks in a running program

I have a question out of curiosity relating to checking for memory leaks.
Being someone who has used valgrind frequently to check for memory leaks in my code for the last year or two, I suddenly came to think that it only detects lost/unfreed memory after the life of the program.
So, in light of that, I was thinking that if you have a long-running program which malloc()'s intermittently and doesn't free() until the application exits, then the potential to eat memory (not necessarily through leaks) is huge and isn't observable using these tools because they only check after the programs lifetime. Are there GDB-like tools which can stop an application while running and check for memory which is and isn't referenced at an instance in the life of the application?
Are there GDB-like tools which can stop an application while running and check for memory which is and isn't referenced at an instance in the life of the application?
Yes: Valgrind.
Specifically, the SVN version of Valgrind has a gdbserver stub embedded into it.
This allows you to do all kinds of cool debugging, not possible before:
You can run program under valgrind and have GDB breakpoints at the same time
You can ask valgrind: is this memory allocated? was this variable initialized?
You can ask valgrind: what new leaks happened since last time I asked for leaks?
I think you can also ask it to list not-leaked new allocations.
What I have done, which was not a tool, for a long-running socket-based server, was to do an operation, but before that print out the amount of free memory, then print it out after my operation, and see if there was any difference.
I knew that in theory my server should have returned all memory used on each call to the server, so if I was the only one calling it, it shouldn't use much more memory than when it started.
You may find that some memory was needed on the first call, so you may want to make several calls, so everything is initialized, then you can do checks like this.
The other option is to create a list of all memory you are mallocing, then when you free it delete from the list that node, and at the end, see which ones still haven't been freed.
That is not generally possible in a language that supports pointer arithmetic, since for example - you could cast an pointer to an integer and back. See http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/pointer.html
Leaked memory is defined as memory that is not referenced by anything in the program.
If you malloced memory and somewhere in your data there is a pointer pointing to that memory it isn't "lost" as far as any automatic check can now.
However, if you allocated memory, never free'ed it but you don't have any pointer pointing to it you have most likely leaked that memory - as there is no way for you to reference it.
Programs like valgrind can find leaks of the kind described above (lost of reference). AFAIK nothing can find "logical" leaks where you still hold a reference to the memory.

stack pointer vs application

Most architectures have a memory map where the user application grows towards
lower memory where the stack grows to the opposite direction. I am wondering what
is happening when I write such a big C-program that all the space for the application
and the is taken away, ie, that stack pointer and application try to write to the same
region in memory? I assume in C something like a segmentation fault occurs? Is there
any processor support that tries to avoid such a problem from happening?
Thanks
No, in C you can get out of memory, which you only notice directly if you actually check the return value of malloc et al. If not, you probably get to dereference a null pointer somewhere, making your app crash. But possibly there may be no immediate visible signs, only your memory gets silently corrupted. Since the memory space for the application is managed by the app itself, the processor/OS can't detect such errors. In modern OSs memory space of the OS itself and of other apps is protected from your app, so if you accidentally try to write to memory outside your own memory space, you are likely to get segmentation fault. But inside your own memory space, it is up to yourself to protect your memory.
The stack pointer is limited. Once it tries to go further than allowed, you typically get a StackOverflow exception or interrupt, leading to program termination. This most commonly happens with runaway recursive functions.
Similarly, space for the stack is reserved, and not accessible to the heap allocator. When you try to do a heap allocation (malloc or new) without enough space, the allocator will typically return NULL or throw an OutOfMemory exception.
I disagree with the answer that says "there will be no immediate visible signs, only your memory gets silently corrupted."
You'll either get a StackOverflow or OutOfMemory, depending on which resource was exhausted first.
Abelenky is correct, modern architectures will trap the stack growing past some limit much smaller than all available address space (this is easy to test with a simple recursive function)
Also, "App grows down, stack grows up" doesn't really describe the memory mapping of multithreaded systems anyway, each thread has it's own stack, which has a pre-set maximium size, and the heap is one or more seperately mapped areas of address space.
The easiest way to figure this stuff out is to attach a debugger to a simple test program; you can see the memory regions used by your process in any decent one. be sure to look where your libraries and code are loaded, as well as more than one thread worth of stack.

Memory overwrite problem

I have one C code app. which i was building using MS-VS2005. I had one output data buffer which was being allocated dynamically using malloc.
For some test cases, the memory size which was being malloc'd was falling short than the the actual output size in bytes which was generated. That larger sized output was written into the smaller sized buffer causing buffer overflow. As a result of which the test-run was crashing with MSVS-2005 showing up a window "Heap corruption ...."
I knew it had to do with some dynamic memory allocation, but i took long time to actually find the root cause, as i did not doubt the memory allocation because i was allocating large enough size necessary for the output. But one particular test case was generating more output than what i had calculated, hence the resulting crash.
My question is:
1.) What tools i can use to detect such dynamic memory buffer over-flow conditions. Can they also help detect any buffer overflow conditions(irrespective of whether the buffer/array is on heap, stack, global memory area)?
2.) Will memory leak tools(like say Purify) or code analysis tools like lint, klocworks would have helped in particular case? I believe they have to be run time analysis tools.
Thank you.
-AD.
One solution, which I first encountered in the book Writing Solid Code, is to "wrap" the malloc() API with diagnostic code.
First, the diagnostic malloc() arranges to allocate additional bytes for a trailing sentinel. For example, an additional four bytes following the allocated memory are reserved and contain the characters 'FINE'.
Later, when the pointer from malloc() is passed to free(), a corresponding diagnostic version of free() is called. Before calling the standard implementation of free() and relinquishing the memory, the trailing sentinel is verified; it should be unmodified. If the sentinel is modified, then the block pointer has been misused at some point subsequent to being returned from the diagnostic malloc().
There are advantages of using a memory protection guard page rather than a sentinel pattern for detecting buffer overflows. In particular, with a pattern-based method, the illegal memory access is detected only after the fact. Only illegal writes are detected by the sentinel pattern method. The memory protection method catches both illegal reads and writes, and they are detected immediately as they occur.
Diagnostic wrapper functions for malloc() can also address other misuses of malloc(), such as multiple calls to free() for same memory block. Also, realloc() can be modified to always move blocks when executed in a debugging environment, to test the callers of realloc().
In particular, the diagnostic wrappers may record all of the blocks allocated and freed, and report on memory leaks when the program exits. Memory leaks are blocks which are allocated by not freed during the program execution.
When wrapping the malloc() API, one must wrap all of the related functions, including calloc(), realloc(), and strdup().
The typical way of wrapping these functions is via preprocessor macros:
#define malloc(s) diagnostic_malloc(s, __FILE__, __LINE__)
/* etc.... */
If the need arises to code a call to the standard implementation (for example, the allocated block will be passed to a third-party, binary-only library which expects to free the block using the standard free() implementation, the original function names can be accessed rather than the preprocessor macro by using (malloc)(s) -- that is, place parentheses around the function name.
Something you can try is allocate enough pages + 1 using VirtualAlloc, use VirtualProtect with PAGE_READONLY | PAGE_GUARD flags on the last page, then align the suspected allocation so the end of the object is near the beginning of the protected page. If all goes well you should get an access violation when the guard page is accessed. It helps if you know approximately which allocation is overwritten. Otherwise it requires overriding all allocations which may require a lot of extra memory (at least 2 pages per allocation). A variation on this technique that I'm hereby christening as "statistical page guard" is to only randomly allocate memory for a relatively small percentage of allocations in that manner to avoid large bloat for small objects. Over a large number of execution runs you should be able to hit the error. The random number generator would have to be seeded off something like time in this case. Similarly you can allocate the guard page in front of the object if you suspect an overwrite at a lower address (can't do both at the same time but possible to randomly mix up as well).
An update: it turns out the gflags.exe (used to be pageheap.exe) microsoft utility already supports "statistical page guard" so i reinvented the wheel :) All you need to do is run gflags.exe /p /enable [/random 0-100] YourApplication.exe and run your app. If you are using a custom heap or custom guards on your heap allocations then you can simply switch to using HeapAlloc at least for catching bugs and then switch back. Gflags.exe is a part of Support Tools package and can be downloaded from the microsoft download center, just do a search there.
PC-Lint can catch some forms of malloc/new size problems, but I'm not sure if it would have found yours.
VS2005 has good buffer overflow checking for stack objects in debug mode (runs at end of function). And it does periodic checking of the heap.
As for it helping to track down where the problems occurred, this is where I tend to start using macro's to dump all allocations to match against the corrupted memory later (when it's detected).
Painful process, so I'm keen to learn better ways also.
Consider our Memory Safety Check. I think it will catch all the errors you describe. Yes, it is runtime checking of every access, with some considerable overhead (not as bad as valgrind we think) with the benefit of diagnosing the first program action that is errorneous.

Resources