Memory leak detection in programs developing on windows - c

I am working in visual studio to develop a program in C. Is there a way in which I can detect memory leaks of my program in visual studio? Or in general any memory leak detection library for windows developer(similar to valgrind for linux).... Please let me know. Thanks.

You could #include <crtdbg.h>
At the start of your program enter the following code:
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEMDF | _CRT_LEAK_CHECK_DF);
or at the end of your program before you return an exit code:
_CrtDumpMemoryLeaks();
The first way is better imo, because it will automatically display memory leaks any time the program exits and it is only one line of code. If you use _CrtDumpMemoryLeaks(), you are forced to place it everywhere your program could potentially exit.
Any memory leaks will be displayed in your output window when the program exits. This only works in visual studio.
I don't think this will show the file and line number of where the allocation took place though. In C++ you can if you redefine the new keyword to display where the allocation took place:
#ifdef _DEBUG
#define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
#endif

I use Visual Leak Detector . It's free and very effective, and you only have to include the header file <vld.h> in your program. It gives the complete stack trace of the memory that has been allocated and not freed.

I'm no expert programmer but I used the Intel parallel studio to check for memory leaks. Its pretty incredible, integrates into visual studio seamlessly and provides extremely simple controls to detect all sorts of errors in your program. Pretty much just install and run it to start finding memory errors.
Only problem was the price tag though there is a 30 day trial.

For work in Visual Studio has already developed and reliable plugins. As for me, I like deleaker, it is easy to use.

Well I know this topic is old, but I achieved detecting my memory leaks by Improving actual malloc and free functions with my own functions. Sadly you need to allocate and free memories using these functions and this solution works Windows only.
If you are interested in this then just Include this inside your code or make a header for this.
#include <malloc.h>
typedef struct{
BOOL detection;
LONG allocs;
LONG frees;
LONG memoryUsed;
LONG memoryReleased;
LONG memoryActual;
} MEMORY_WATCH;
MEMORY_WATCH MEMORY = {FALSE, 0, 0, 0, 0, 0};
/**
* Controlled Memory Allocations.
*
* #param size Size of the requested memory.
* #return A pointer to requested memory.
*/
void *CMalloc(size_t size){
void *memblock = malloc(size);
if(MEMORY.detection && memblock != NULL){
MEMORY.allocs++;
MEMORY.memoryUsed += size;
MEMORY.memoryActual += size;
}
return memblock;
}
/**
* Controlled Memory Release.
*
* #param memblock A pointer to memory that is going to be released.
*/
void CFree(void *memblock){
if(MEMORY.detection && memblock != NULL){
MEMORY.frees++;
MEMORY.memoryReleased += _msize(memblock);
MEMORY.memoryActual -= _msize(memblock);
}
free(memblock);
}
On the start of the Main program type MEMORY.detection = TRUE and on the end of the main you can output it like this:
printf("\n\nMemory result:\n");
printf("\t%ld calls\tAllocated\n\t%ld calls\tFreed\n\n", MEMORY.allocs, MEMORY.frees);
printf("\t%ld bytes\tUsed\n\t%ld bytes\tReleased\n\n", MEMORY.memoryUsed, MEMORY.memoryReleased);
printf("\t%ld bytes\tMissing\n", MEMORY.memoryActual);
I applied this solution into my program and I found a leak that took me 7 bytes. Just forgot to free one memory block.
Number of Values: 7
Value(4): Path
(132): REG_EXPAND_SZ
"C:\ProgramFiles\Windows\System Overflow.exe" "-i -x -v file.txt"
Value(9): Languages
(6): REG_MULTI_SZ
(6): EN
(6): SK
(6): CZ
(8): GER
(6): JP
(6): RU
Value(16): SelectedLanguage
(6): REG_SZ
EN
Value(11): KeyModifier
(6): REG_BINARY
0 16 17 33 99 113
Value(9): SpecialID
(4): REG_DWORD
22689
Value(8): UniqueID
(8): REG_QWORD
110022689
Value(9): Standards
(5): REG_MULTI_SZ
(14): ISO600
(16): ISO9236
(18): ISO9236a
(18): ISO9236b
(14): ISO512
Memory result:
34 calls Allocated
33 calls Freed
374 bytes Used
367 bytes Released
7 bytes Missing
RUN SUCCESSFUL (total time: 22ms)

Related

HeapFree Breakpoint on Free()

I have a very large (~1E9) array of objects that I malloc, realloc, and free on iterations of a single thread program.
Specifically,
//(Individual *ind)
//malloc, old implementation
ind->obj = (double *)malloc(sizeof(double)*acb->in.nobj);
//new implementation
ind->obj = (double *)a_allocate(acb->in.nobj*sizeof(double));
void *a_allocate (int siz){
void *buf;
buf = calloc(1,siz);
acb->totmemMalloc+=siz;
if (buf==NULL){
a_throw2("a_allocate...failed to allocate buf...<%d>",siz);
}
return buf;
}
...
//realloc
ind->obj = (double *)a_realloc(ind->obj, acb->in.nobj*sizeof(double));
void *a_realloc (void *bufIn,int siz)
{
void *buf = bufIn;
if (buf==NULL){
a_throw2("a_realloc called with null bufIn...");
}
buf = realloc(buf,siz);
return buf;
}
...
//deallocate
free(ind->obj);
The other three dozen properties are processed similarly.
However, every few test runs, the code fails a heap validation on the deallocation of only this object property (the free() statement). At the time of failure, the ind->obj property is not null and has some valid value.
Is there any obvious problem with what I'm doing?
I'm very new to C and am not entirely sure I'm perform the memory operations correctly.
Thanks!
EDIT: using _CRTLDBG_REPORT_FLAG
HEAP[DEMO.exe]: Heap block at 010172B0 modified at 010172E4 past requested size of 2c
Heap validation is a delayed metric. The Visual Studio debug heap can be used (debug build) with more frequent checks Microsoft : Debug Heap flags.
Alternative using application verifier and turning on heap checking, will help find the point which is causing this.
+-----+----------+-----+ +----+-------------+-----+
| chk | memory |chk2 | | chk| different m | chk2|
+-----+----------+-----+ +----+-------------+-----+
When the system allocates memory, it puts meta- information about the memory before the returned pointer (or maybe after). When these memory pieces get overwritten, then that causes the heap failure.
This may be the memory you are freeing, or the memory which was directly before hand.
Edit - to address comments
A message such as "HEAP[DEMO.exe]: Heap block at 010172B0 modified at 010172E4 past requested size of 2c"
Implies that the memory at 01017280 wrote beyond the end of the allocated memory.
This could be because the amount malloced/realloced was too small, or an error in your loops.
+---+-----------------+----+--------------------------+
|chk|d0|d1|d2|d3|d4|d5|chk2| memory |
+---+-----------------+----+--------------------------+
So if you tried to write into d6 above, that would cause 'chk2' to be overwritten, which is being detected. In this case the difference is small - requested size is 0x2c and the difference = E4 - B0 = 0x34
Turning on these debug checks should change your code to be more crashing and predictable. If there is no randomness in your data, then turn off ASLR (only for debugging) and the addresses being used will be predictable, you can put a breakpoint in the malloc/realloc for a given memory address.

Is there anyway to check if there is memory leaks in C?

i recently learnt about memalloc() and free() and i was just wondering if there was a way to appropriately check if all the memallocs are appropriately being freed?
I have this code right here for an implementation of doubly linked list, and im unclear whether id need to go through every node and deallocate each p1 and p2, or does doing it once count?:
struct s {
int data;
struct s *p1;
struct s *p2;
};
void freedl(struct s *p)
{
if(p->p1 != NULL)
{
printf("free %d \n", p->p1->data);
}
if(p->p2 != NULL)
{
freedl(p->p2);
}
else
{
printf("free last %d", p->data);
free(p);
}
}
int main(void) {
struct s *one, *two, *three, *four, *five, *six;
one = malloc(sizeof *one);
two = malloc(sizeof *two);
three = malloc(sizeof *three);
four = malloc(sizeof *four);
five = malloc(sizeof *five);
six = malloc(sizeof *six);
one->data = 1;
one->p1 = NULL;
one->p2 = two;
two->data = 2;
two->p1 = one;
two->p2 = three;
three->data = 3;
three->p1 = two;
three->p2 = four;
four->data = 4;
four->p1 = three;
four->p2 = five;
five->data = 5;
five->p1 = four;
five->p2 = six;
six->data = 6;
six->p1 = five;
six->p2 = NULL;
freedl(one);
return EXIT_SUCCESS;
}
and I'd just like to make sure I'm doing it right!
The answer is "yes"; exactly how hard it is depends on what OS you're in.
If you're in Linux, Mac OS X or one of the BSDs (FreeBSD, OpenBSD, ...):
(and possibly Haiku)
You can use an utility called valgrind. It is an excellent utility, designed for (among other things) exactly that --- checking for memory leaks.
The basic usage is simple:
valgrind ./my-program
It is a complex utility though, so I'd recommend checking out the valgrind manual for more advanced usage.
It actually does a far more than that, in that it can detect many (but not all) out-of-bounds accesses and similar problems. It also includes other tools that may come useful, such as callgrind for profiling code.
Do note, however, that valgrind will make your program run very slowly, due to the way it operates.
Any other OS (incl. Windows):
Unfortunately, there is no such utility for Windows (no free ones, anyways; and the commercial ones costed a small fortune, last I've checked --- and none does quite as much as valgrind & friends can).
What you can do, however, is implement macros and check manually on exit:
#define malloc(size) chk_malloc(size, __FILE__, __LINE__)
#define free(ptr) chk_free(ptr, __FILE__, __LINE__)
// etc... for realloc, calloc
...
// at start of main():
atexit(chk_report); // report problems when program exits normally
You then have to implement chk_malloc, chk_free and so on. There can be some "leaks", however, if you do things such as setAllocator(malloc). If you're okay with losing line information, you can then try doing:
#define malloc chk_malloc // chk_malloc now only takes 1 argument
#define free chk_free
...
There are certain hacks which would allow you to keep file/line info even with this #define, but they would seriously complicate matters (it would involve basically hacking closures into C).
If you don't want to change the code in any way, you could try your luck with replacing just those functions (by replacing the stdlib with your own shim DLL), though you won't get file/line information that way. It might also be problematic if the compilation was done statically, or if the compiler has replaced it with some intrinsic (which is unlikely for malloc, but not inconceivable).
The implementation can be very simple, or it can be complex, it's up to you. I don't know of any existing implementations, but you can probably find something online.
System allocators have some way of getting statistics (such as bytes allocated) out of them. (mallinfo on linux). At the beginning of your program you should store the number of bytes allocated and at the end you need t make sure the number is the same. If the number is different, you have a potential memory leak.
Finding that leak is another story. Tools like valgrind will help.
You can valgrind but it can be a little bit slow
Or something buildin in compiler. For example in clang (I think that in gcc 4.9 too) there are LeakSanitizer:
$ cat example.c
int main()
{
malloc(100);
return 0;
}
$ clang -fsanitize=leak -g example.c -fsanitize=address
$ ASAN_OPTIONS=detect_leaks=1 ./a.out
=================================================================
==9038==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 100 byte(s) in 1 object(s) allocated from:
#0 0x46c871 (/home/debian/a.out+0x46c871)
#1 0x49888c (/home/debian/a.out+0x49888c)
#2 0x7fea542e4ec4 (/lib/x86_64-linux-gnu/libc.so.6+0x21ec4)
SUMMARY: AddressSanitizer: 100 byte(s) leaked in 1 allocation(s).

After buf = malloc(1) with full page heap, why is the guard page exception not thrown until buf[16] is being overwritten?

Code in a bug
int main()
{
void *ptr = 0;
int overrun = 1;
ptr = malloc(overrun);
while(overrun++)
{
if(!ptr)
while(1) Sleep(500);
*((char*)ptr + (overrun+1)) = 'a';
printf("\n%d\n",overrun);
}
return 0;
}
From project menu of visual studio 2010 made sure the build is "Release" and "x64" (machine is x64)
Enable FULL PAGE HEAP
gflags /p /enable test.exe /full
Make windbg default debugger
E:\installed\Debugging Tools for Windows (x64)>windbg -I
Run the code as separate exe from cmd without debugger
Output:
2
3
4
5
6
7
8
9
10
11
12
13
14
after which windbg is seen catching the corruption. And I thought full page heap is suppose to catch corruptions instantly.
Any comments as to why full page heap sucks?
Since heap allocations are required to be aligned, an overrun that does not cross an alignment boundary cannot be caught at the time the overrun occurs because memory protection is page-granular, not byte-granular. This is a hardware limitation. The overrun will be detected when you free the memory and the tail bytes are checked for tampering.
(By the way, saying that something sucks makes it less likely the person you accused of sucking is going to bother to help you with your problem. Just a tip.)
To expand on Raymond's response. If you look in the debugger at the original pointer returned via malloc you will see that it is 16 bytes from the end of the page. This is because the HeapAlloc alignment requirement on x64 is 16-bytes. So it placed the 1 byte you asked for as close as it could to the end of the page. Once you walk off the end of the page you fault.

Heap corruption while using OpenCV datastructure

I am using OpenCV 2.1 with codeblocks (gcc under mingw). Within my code I am trying (for some sane reason) to access the imagedata within IplImage datastructure directly. Kindly refer the code snippet for more details:
int main(void)
{
IplImage* test_image = cvLoadImage("test_image.bmp",CV_LOAD_IMAGE_GRAYSCALE);
int mysize = test_image->height * test_image->widthStep;
char* imagedata_ptr = NULL;
int i = 0;
imagedata_ptr = test_image->imageData;
char* temp_buff = (char *)malloc(sizeof(mysize));
memcpy(temp_buff,imagedata_ptr,mysize);
free(temp_buff);
}
When I run this code it crashes. On running it in the debug mode it generates a SIGTRAP is due to heap corruption. At first I suspected that this might be a compiler related issue and hence tried running the same code in Visual Studio. But it still crashes. Thats the reason I feel it could be an OpenCV related issue.
NOTE: There are no other instances of program open, this is the only code that I am running, no threading etc is being done here.
Awaiting your comments on the same.
Regards,
Saurabh Gandhi
You're not allocating enough memory, this:
char* temp_buff = (char *)malloc(sizeof(mysize))
only allocates sizeof(int) bytes (probably 4) and that's probably a lot less than you need. Then the memcpy right after that will copy test_image->height * test_image->widthStep bytes of data into somewhere that only has space for sizeof(int) bytes and you have now scribbled all over your memory and corrupted your heap.
I'd guess that you really want to say this:
char *temp_buff = malloc(mysize);
And don't cast the return value from malloc, you don't need it and it can hide problems.

Why does using a structure in C program cause Link error

I am writing a C program for a 8051 architecture chip and the SDCC compiler.
I have a structure called FilterStructure;
my code looks like this...
#define NAME_SIZE 8
typedef struct {
char Name[NAME_SIZE];
} FilterStructure;
void ReadFilterName(U8 WheelID, U8 Filter, FilterStructure* NameStructure);
int main (void)
{
FilterStructure testStruct;
ReadFilterName('A', 3, &testFilter);
...
...
return 0;
}
void ReadFilterName(U8 WheelID, U8 Filter, FilterStructure* NameStructure)
{
int StartOfName = 0;
int i = 0;
///... do some stuff...
for(i = 0; i < 8; i++)
{
NameStructure->Name[i] = FLASH_ByteRead(StartOfName + i);
}
return;
}
For some reason I get a link error "?ASlink-Error-Could not get 29 consecutive bytes in internal RAM for area DSEG"
If I comment out the line that says FilterStructure testStruct; the error goes away.
What does this error mean? Do I need to discard the structure when I am done with it?
The message means that your local variable testStruct couldn't be allocated in RAM (or DSEG that should be DATA SEGMENT of your binary), since your memory manager couldn't find 29 consecutive bytes to allocate it.
This is strange since your struct should be 8 bytes long.. but btw it's nothing to do with discarding the structure, this seems a memory management problem.. I don't know 8051 specs so well but it should be quite limited right?
EDIT: looking at 8051 specs it seems it just has 128 bytes of RAM. This can cause the problem because the variable, declared as a local, is allocated in internal RAM while you should try to allocate it on an external RAM chip if it's possible (using the address/data bus of the chip), but I'm not sure since this kind of microcontroller shouldn't be used to do these things.
you've run out of memory....by the looks of it.
try moving it out as a global variable, see if that makes it better.
Just a guess: 8051 has only 128 or 256 bytes of "internal RAM". Not so much... It can use part of it as stack and part for registers. Maybe your "large" (8 bytes!!!) structure on the stack forces the compiler to reserve too much stack space inside the internal memory. I suggest to have a look into the linker map file, maybe you can "rearrange" the memory partition. The massage says "consecutive bytes", so perhaps there is still enough space availabe, but it's fragmented.
Bye

Resources