1、代碼邏輯不清晰,if嵌套過多。
2、代碼邏輯不清晰,邏輯代碼書寫較為分散
rc = sqlite3_open(DB_NAME, &db); //邏輯分散
if (rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return cJSON_CreateObject();
}
cJSON * p;
p = cJSON_GetObjectItem(params, "action");
if (p == NULL)
return cJSON_CreateObject(); //存在資源泄漏問題
else
PowerPolicy = p->valueint;//邏輯不清晰導致if過多
string sql = "";
建議寫法:
cJSON * p = cJSON_GetObjectItem(params, "action");
if(p == NULL)
return cJSON_CreateObject();
int powerpolicy = p->valueint;
int rc= sqlite3_open(DB_NAME, &db); //邏輯分散
if (rc) {
fprintf(stderr, "Can't open database");
return cJSON_CreateObject();
}
...
3、調試日志不規范。
建議:
調試時候 打印時間戳,線程號,當前文件和行號,調試信息,可如下設計API
c實現
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>
#include <pthread.h>
void _debug(const char *filename,int line,const char *fmt,...)
{
char buf[1024];
va_list ap;
va_start(ap,fmt);
vsnprintf(p,size,fmt,ap);
va_end(ap);
time_t t = time(NULL);
printf("%u-%s:%d-%p %s\n",t,filename,line,pthread_self(),buf);
}
.h頭文件
#define debug(fmt,...) _debug(__FILE__,__LINE__,fmt,__VA_ARGS__)
4、API接口設計不合理,沒有遵循誰申請,誰釋放原則。
cJSON* send_request(char const *ip,uint16_t port,char const *method,int id, cJSON* params)
1、不應該在send_request
中釋放參數申請的內存。
2、返回參數最好傳入指針。(副作用,不釋放)
5、代碼中沒有處理好定時和異步任務。
1、能不用信號的地方,就不要用信號。
2、框架上有定時器,必要的時候可以增加API
6、調試技巧
1 查看資源占用情況
1. top
2 lsof
3 進入/proc/pid/ 查看線程數量。
有異常處理異常。
gdb 抓到信息發現比較難分析的話,就放棄gdb,利用日志解決。