MySQL C API mysql_free_result() 详解

来源:互联网 发布:公安民警网络答题 编辑:程序博客网 时间:2024/06/05 03:24

MySQL C API mysql_free_result() 详解

MySQL C API mysql_free_result() 


mysql_free_result()會釋放先前查詢所儲存的資料集(result set),但是它並不會在釋放後變更該資料集的指標。 
mysql_free_result() 應該是只被呼叫一次而已,如果程式設計者忘了,而多呼叫它,這樣會導致 mysql_free_result() 去嘗試釋放未分配的記憶體空間,而發生嚴重的錯誤。 
C/C++的變數,如果是自動變數時,並不會有預設的初值,對指標而言尤其重要。為每個變數設定其初值是良好的習慣,通常,我們會把指標的初值設為 NULL,在使用完某個由我們分配出的記憶體空間之後,必須要釋放它。一個好習慣是:給予初值,在用完且釋放後,再還給它初值。 
我們可以在使用 mysql_store_result() 之前,就把 result set 變數設為 NULL,在用完後用 mysql_free_result() 去釋放它,並且把 result set 再設回為初值 NULL。這樣可以保證我們不會因一時的程式撰寫錯誤,而多釋放一次已被釋放的 result set。 

Example:
MYSQL mysql;
MYSQL_RES *res;
 MYSQL_ROW row; 
res = NULL; // Set res as default NULL    
mysql_init(&mysql);  
mysql_real_connect(&mysql,"localhost","root","","test",0,NULL,0);  
mysql_query(&mysql,"SELECT * FROM person WHERE no<'10'");  
res = mysql_store_result(&mysql);  
..... other code here.....  ... maybe check res is NULL or not  .......  mysql_free_result(res);  
res = NULL; // Set res as default NULL  
....  mysql_close(&mysql);    ////////////  // Notes:  If result is NULL, 
we call mysql_free_result(res) is ok.  
If call mysql_free_result(res) more then once,   
we can get an memory access error.    
Example:(OK)  res = mysql_store_result(&mysql);  
......  mysql_free_result(res);   // call free result once  res = NULL;  
....  mysql_free_result(res);   // call free result more then once is ok,  
// because we set res as default NULL when after call mysql_free_result()    
Example:(BAD,ERROR)  
res = mysql_store_result(&mysql);  
......  mysql_free_result(res);   
// must call free result once  
....  mysql_free_result(res);  
// call free result more then once is BAD, 
 // because res is unallocated now. 
0 0
原创粉丝点击