OS API distributes elements in the structure. Free only the structure or each member?

Let's say we have an array PRINTER_INFO_2

like this:

PRINTER_INFO_2* printers = (PRINTER_INFO_2*)malloc(sizeof(PRINTER_INFO_2) * 64); // room for 64 items

      

We then call EnumPrinters()

to get a list of locally installed printers:

EnumPrinters(
    PRINTER_ENUM_LOCAL,
    NULL,
    2,
    (LPBYTE)printers,
    ...);

      

Here's the structure information for PRINTER_INFO_2

. The members of the string are now of type LPTSTR, so they are not stored inside the structure itself.

Now I am wondering if I can just call free(printers)

when I am done with this, or it will leak memory (all these lines are not freed)?

Do I need to call free()

for each member of the string like below?

free(printers[i].pServerName);
free(printers[i].pPrinterName);
free(printers[i].pShareName);
...
free(printers);

      

Seems terribly difficult to me this way. Especially if there are many, many members in the structure that need to be released.
Is there a better way to do this?

Thanks for helping me with this!

+2


source to share


1 answer


IIUC, you need to concatenate the buffer outside the size of the structure to accommodate any output lines. EnumPrinters will tell you if the memory block was too small. Since you cannot know in advance how much memory you need, you usually call it twice: once to find out how much memory you need, and the second time with a buffer of the appropriate size. Then you free the buffer using the same API you used to allocate (like malloc / free).



+1


source







All Articles