最近公司开发的code defect工具,扫出很多asprintf的问题,下面是sample code
int testAsprintf(int num) {
char *testStr = NULL;
asprintf(&testStr, "%d", num);
// use testStr doing something
if (testStr != NULL) {
free(testStr);
testStr = NULL;
}
return 1;
}
看过code之后,想到的应该是testStr在asprintf之后没有判断是否是NULL,所以马上改了一版。
int testAsprintf(int num) {
char *testStr = NULL;
asprintf(&testStr, "%d", num);
if(testStr == NULL) {
return 0;
}
// use testStr doing something
if (testStr != NULL) {
free(testStr);
testStr = NULL;
}
return 1;
}
自认为上面的code没有问题了,asprintf函数经常用,知道需要free,在加上判断条件简直是完美的sample。今日有些时间在网上看了一下asprintf的原型和解释:
**#include <stdio.h>
int asprintf(char **strp, const char *fmt, …);
int vasprin