MYSQL client program design errors to be avoided [group chart] this article discusses some common MySQLC API Program design errors, and how to avoid it (these problems occur cyclically in the MySQL mail list ).
1. Error 1-use uninitialized connection handler pointer
We have passed the NULL parameter to call mysql _ I n I t (). This is to let it allocate and initialize the MYSQL structure, and then return a pointer. Another method is to pass the pointer to an existing MYSQL structure. In this case, mysql_init () initializes the structure and returns a pointer without having to allocate the structure itself. If you want to use the second method, be careful when there are some subtle problems. The following discussion points out some issues that need attention. If you pass a pointer to mysql _ init (), it should actually point to something. See the following code snippet:
This problem is that mysql_init () gets a pointer, but the pointer does not point anywhere you know. Conn is a local variable. Therefore, when main () starts execution, it is an uninitialized memory that can point to any place. This means mysql_init () will use a pointer, you can overwrite data in any area of the memory. If you are lucky, the conn points to the external address space of your program, so that the system will immediately terminate, so that you can be aware of problems in the code as soon as possible.
If unfortunately, the conn points to the internal data that will not be used in the program until the data is used again. Therefore, the actual problems are far more difficult to capture than the problems encountered during program execution. The following is a piece of problematic code:
Conn is a global variable. Therefore, before the program starts, it is initialized to 0 (that is, NULL ). Mysql_init () encounters a NULL parameter, so a new connection handler is initialized and assigned. The system crashes as long as the conn is passed to the MySQLCAPI function that requires a non-NULL connection handler. The modification of these code segments is to ensure that conn has a known value. For example, you can initialize it to the allocated MYSQL schema address: