0

My app's memory usage goes up permanently, each time I create a keyboard event using Quartz Event Services.

The following is the problematic code inside of an infinite loop:

int keyCode = 0;
BOOL keyDownBool = FALSE;

while (TRUE) {


    /* creating a keyboard event */

    CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStatePrivate);

    CGEventRef keyboardEvent =
    CGEventCreateKeyboardEvent(source, (CGKeyCode)keyCode, keyDownBool);

    CFRelease(source);
    CFRelease(keyboardEvent);



}

Instruments.app says that there are no memory leaks...

What is the problem here?

Thank you for your help!

simsula
  • 147
  • 7
  • Possible duplicate of [Why does my c program not free memory as it should?](https://stackoverflow.com/questions/447899/why-does-my-c-program-not-free-memory-as-it-should) – Willeke Aug 03 '18 at 12:26
  • 1
    The event source and the event are reusable. Create one event source if you want to send many events. Create one event i you want to send the same event over and over again. – Willeke Aug 03 '18 at 12:28
  • @Willeke yep that was it. Only creating CGEventSource once and then reusing it fixes the problem. Thanks! – simsula Aug 03 '18 at 12:36

1 Answers1

0

Okay so the solution is pretty simple. You only need to create your CGEventSourceRef once, and then you can reuse it each time you want to post an event. Creating your CGEventSourceRefover and over again causes the "leaks" to happen.

The proper code looks like this:

int keyCode = 0;
BOOL keyDownBool = FALSE;


CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStatePrivate);



while (TRUE) {


    /* creating a keyboard event */


    CGEventRef keyEvent =
    CGEventCreateKeyboardEvent(source, (CGKeyCode)keyCode, keyDownBool);


    CFRelease(keyEvent);



}

Thanks to @Willeke for the suggestion.

simsula
  • 147
  • 7