areify
areify

Reputation: 196

How to avoid a memory leak in this code?

I've the next code, at the click event of a button:

         PNIO_DEV_ADDR addr;
         addr.AddrType = PNIO_ADDR_GEO;     //Para IO Device
         addr.IODataType = PNIO_IO_OUT;     //Escritura en PLC
         addr.u.Geo.Slot = (int)(numericUpDownSlot->Value);
         addr.u.Geo.Subslot = (int)(numericUpDownSubslot->Value);

         CP1626::write(&addr);

PNIO_DEV_ADDR is a C struct, and write is a function linked to a DLL callback, which asks for a PNIO_DEV_ADDR* parameter.

Each time I press the button I can see at the task manager how the memory associated to my app increases a few bytes.

I've googled and read a lot about pointers and references but I don't quite understand what I'm doing wrong.

Could you explain me where is the problem, please?

P.S.: I'm using a C library (built on a DLL) and a C++/CLI application.

Thank you in advance.

EDIT:

PNIO_DEV_ADDR is:

typedef struct {
    PNIO_ADDR_TYPE  AddrType;
    PNIO_IO_TYPE    IODataType;
    union {
        PNIO_UINT32 Addr;
        struct {
            PNIO_UINT32 reserved1[2];
            PNIO_UINT32 Slot;
            PNIO_UINT32 Subslot;
            PNIO_UINT32 reserved2;
        } Geo;                   /* geographical address */
    } u;
} ATTR_PACKED PNIO_DEV_ADDR;

When the two first variables are enums.

EDIT2:

This is the entry point of the function write inside the DLL:

PNIO_UINT32 write(PNIO_DEV_ADDR* addr){
    PNIO_UINT32 result;

    result = PNIOD_trigger_data_write_sync(g_devHndl, addr, PNIO_ACCESS_RT_WITH_LOCK);

    return result;
}

PNIO_trigger_data_write_sync requires a PNIO_DEV_ADDR*. Sorry but I can't access inside this function because it is on a different DLL which is third party. Should I've copied the addr pointer?

Upvotes: 0

Views: 77

Answers (1)

Abhijit Pritam Dutta
Abhijit Pritam Dutta

Reputation: 5591

There are two kinds of memory allocation in C/C++, one is memory allocation during compile time and other one is dynamic memory(memory allocation during run time) allocation and I am sure you know about this. memory allocation during compile is done form stack of an application and dynamic memory allocation is done from heap of an application. We need to concern about memory release which is allocated (dynamically) from heap to avoid memory leak. For memory release from stack compiler automatically manage it.

In your case the allocation is done from stack. Hence once the control go out of the scope of the method where your current codes are, it will automatically release the memory of stack.

Now in your case PNIO_DEV_ADDR addr;, this is compile time memory allocation and is not dynamically allocated memory at all. So it will not leads to memory leak.

Inside the dll method, I am sure it has copied your object to its local object.

Upvotes: 1

Related Questions