I have a code snippet which connects to a MySQL database like this (not directly from code so there might be typos):
m_connectionHandler = mysql_init(NULL);
if (m_connectionHandler == NULL)
{
// MySQL initialization failed
return;
}
MYSQL *tmp = mysql_real_connect(m_connectionHandler,
m_hostname,
m_username,
m_password,
m_dbName,
m_port,
NULL,
m_flags);
if (tmp == NULL)
{
// Connect failed
mysql_close(m_connectionHandler);
return;
}
My question is if mysql_close (in the second if clause tmp == NULL), in the case when mysql_real_connect returns NULL, is required, or if mysql_real_connect frees the connection handler for me upon failure?
The documentation does state that what you get from mysql_init should be freed by mysql_close, but there are indications that it's already freed by mysql_real_connect upon failure.
Can anyone shed some light on this for me?
Your call to mysql_init(NULL) allocates memory. Regardless of whether you're able to really connect to the server, you've still allocated memory, so you need to free it with mysql_close, which not only closes connections but also releases memory. I see no indication in the documentation that mysql_real_connect would free the memory itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With