Skip to content

Commit f603e3f

Browse files
committed
Move a struct from heap to stack, since the caller will outlive its callees anyway
1 parent f741be7 commit f603e3f

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

Frameworks/SPMySQLFramework/Source/SPMySQLConnection Categories/Ping & KeepAlive.m

+9-8
Original file line numberDiff line numberDiff line change
@@ -159,19 +159,21 @@ - (BOOL)_pingConnectionUsingLoopDelay:(NSUInteger)loopDelay
159159
if (timeout > 0) pingTimeout = timeout;
160160

161161
// Set up a struct containing details the ping task will need
162-
SPMySQLConnectionPingDetails *pingDetails = malloc(sizeof(SPMySQLConnectionPingDetails));
163-
pingDetails->mySQLConnection = mySQLConnection;
164-
pingDetails->keepAliveLastPingSuccessPointer = &keepAliveLastPingSuccess;
165-
pingDetails->keepAlivePingThreadActivePointer = &keepAlivePingThreadActive;
166-
pingDetails->parentId = self;
162+
// we can do this on the stack since this method makes sure to outlive the ping thread
163+
SPMySQLConnectionPingDetails pingDetails = {
164+
.mySQLConnection = mySQLConnection,
165+
.keepAliveLastPingSuccessPointer = &keepAliveLastPingSuccess,
166+
.keepAlivePingThreadActivePointer = &keepAlivePingThreadActive,
167+
.parentId = self
168+
};
167169

168170
// Create a pthread for the ping
169171
pthread_t keepAlivePingThread_t;
170172

171173
pthread_attr_t attr;
172174
pthread_attr_init(&attr);
173175
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
174-
pthread_create(&keepAlivePingThread_t, &attr, (void *)&_backgroundPingTask, pingDetails);
176+
pthread_create(&keepAlivePingThread_t, &attr, (void *)&_backgroundPingTask, &pingDetails);
175177

176178
// Record the ping start time
177179
pingStartTime_t = mach_absolute_time();
@@ -200,13 +202,12 @@ - (BOOL)_pingConnectionUsingLoopDelay:(NSUInteger)loopDelay
200202
}
201203
} while (keepAlivePingThreadActive);
202204

203-
//wait for thread to go away, otherwise our free() below might run before _pingThreadCleanup()
205+
//wait for thread to go away, otherwise pingDetails may go away before _pingThreadCleanup() finishes
204206
pthread_join(keepAlivePingThread_t, NULL);
205207

206208
// Clean up
207209
keepAlivePingThread_t = NULL;
208210
pthread_attr_destroy(&attr);
209-
free(pingDetails);
210211

211212
// Unlock the connection
212213
[self _unlockConnection];

0 commit comments

Comments
 (0)