21.8.7.20 mysql_fetch_lengths()

unsigned long *mysql_fetch_lengths(MYSQL_RES
*result)

Description

Returns the lengths of the columns of the current row within a
result set. If you plan to copy field values, this length
information is also useful for optimization, because you can
avoid calling strlen(). In addition, if the
result set contains binary data, you
must use this function to
determine the size of the data, because
strlen() returns incorrect results for any
field containing null characters.

The length for empty columns and for columns containing
NULL values is zero. To see how to
distinguish these two cases, see the description for
mysql_fetch_row().

Return Values

An array of unsigned long integers representing the size of each
column (not including any terminating null characters).
NULL if an error occurred.

User Comments

While the above example doesn't show it, it's probably a good idea to malloc() the lengths variable using lengths = malloc( sizeof( unsigned long ) * num_fields ) prior to packing your column lengths in, and free()'ing it after you're done with them.

I say 'probably' a good idea, because I'm honestly not sure. The MYSQL_RES type with mysql_store_result automatically allocated the memory.

malloc acquires some memory and returns a pointer to that memory. The call to fetch_lengths is going to overwrite that pointer.

A subsequent call to free using the value now in the lengths stack variable is going to attempt to free some memory inside the result structure. Exactly what would happen then I can't be bothered to investigate. I think, stress think, that free will give up 'cos it won't recognize the address passed to it.

The bad news is the pointer to malloced memory has now gone walkies and a memory leak has been created - whoops <g>