Createpen Doesn't Create Memory Leaks?

I've created a HPEN and selected it with the following code:

HPEN hPen = CreatePen(PS_SOLID, 1, RGB(0,0,0));
oldPen = (HPEN)SelectObject(hdc, hPen);

After this i'm drawing something and selecting the old Pen:

SelectObject(hdc, oldPen);

To see memory leaks i use:

#define CRTDBG_MAP_ALLOC
#include <crtdbg.h>

/* This in the main function */
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );

If i close the application no mem leak will be shown. But i thought if i don't delete the object with DeleteObject() i get memory leaks.

I've tested the flag with this and it worked:

int* leak = new int;

So there can't be a problem with the flag. Can you help me with this problem or tell me more about why no mem leak is shown?

Thank you!

1

2 Answers

CreatePen is a win32 api function that (potentially) allocates some memory inside the windows kernel to be used while drawing. The memory allocated with new / new[] is allocated by the C Run-Time Library so it will be catch by the CRT debug functions. They were specifically created to catch memory leaks allocated with malloc / new / new[]

1

As others have stated, you will not be able to track down GDI leaks this way.

I personally use GDIView for this purpose and am satisfied with it ( if others can recommend other tools for tracking down GDI leaks I would appreciate it ).

Also, you will need to delete the pen after you finish using it ( DeleteObject(hPen) ).

Best regards.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest