tags:

views:

131

answers:

1

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?

+1  A: 

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.

Rob Kennedy
I finally checked through the source and it appears that they do some free'ing of memory at the bottom of `mysql_real_connect`, but it is not at all clear that it does everything that `mysql_close` does, so I'll accept this answer.
Erik Edin