Question

I have an issue of finding out of who is allocating memory to the variable in an extremely large code base in visual studio. For Example: I have a structure

struct test
{
    char *point;
}*obj;

obj = malloc(sizeof(struct test));
obj->point = malloc(100);

Variable obj is passed around the entire code, and at some place obj->point is reallocated without freeing the old memory. However, this happens at so many locations that it is impossible to keep track of which one is actually doing it. Is there anyway in visual studio, to keep a conditional breakpoint, where I will get notified if the old memory is replaced with a new one

Was it helpful?

Solution

If there's a specific object you want to track than you can set up a data breakpoint on &obj->point. Whenever this pointer changes the debugger will stop the application.

In Visual Studio, place a regular breakpoint when your obj is created. Go to the breakpoints window and select "New->New Data Breakpoint". For the address enter &obj->point and select the data size (4/8 for 32/64 bit).

OTHER TIPS

You can do this by using a wrapper function for malloc and adding additional parameters to the wrapper which shows the memory allocation and the location of code/process id which allocated it.

Otherwise you can consider using the debug version of malloc in visual studio whichis given below.

Use _malloc_dbg defined in . This is just the malloc with additional parameters for filename and linenumber to print out or keep track of the location. This will help you in debugging.

void *_malloc_dbg
(
    size_t size,
    int blockType,
    const char *filename,
    int linenumber 
);

All these options makes you rework on code where malloc is done.

Another option I guess would be to painfully break the malloc each time it is called and see whenever the memory address location is accessed again. Hope there is no dynamic changing of memory locations in your code base which maybe done and kept track by the memory management module if present. If not you can check the address location repeating again and at that point you can use the call stack in visual studio to further debug it.

One small idea I have is to write a small code to save the address location being allocated whenever you use the malloc for this particular variable. This can be done using a global variable which is set before you allocate the memory for which you need to track. If that variable is set then always save that memory address and compare with that address whenever the memory is hit again. This can be done if you have used a memory wrapper in your code for all the memory management.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top