1. 对const修饰的变量赋值
定义如下一个const修饰的数组,并对该数组memset
const char a[10];
memset(a, 0, sizeof(a));
2. free static修饰的变量
代码举例如下:
static char *ptr = NULL;
ptr = (char*)malloc(10);
free(ptr);
ptr = NULL;
3. 函数参数未判空
举例如下:
void func(void *name)
{
strcpy(name, "andy");
}
为安全起见, 应该要判断 name 是否空指针。代码实现如下:
void func(void *name)
{
if (NULL==name)
{
return ;
}
strcpy(name, "hello");
}
4. 函数返回值未判空
如下代码,如果 content中不包含“hello”,则strstr返回NULL,此时对startIndex操作就会出段错误。
startIndex = strstr(content,"hello");
strcpy(newValue, startIndex);
比较安全的处理为:
startIndex = strstr(content,"hello");
if (startIndex)
{
strcpy(newValue, startIndex);
}
5. 使用不安全的库函数
strcat, strcpy, printf等都是不安全的库函数。比如:
char a[5];
strcpy(a, "hello word");
6. 野指针
错误实现如下:
void func1(char *ptr)
{
free(ptr);
ptr = NULL;
}
void func2()
{
char *ptr = NULL;
ptr = malloc(10);
if (NULL!=ptr)
{
func1(ptr);
strcpy(ptr, "hello");
}
}
7. double free
错误实现如下:
void func1(char *ptr)
{
....
free(ptr);
ptr = NULL;
}
void func2()
{
char *ptr = NULL;
ptr = malloc(10);
if (NULL!=ptr)
{
func1(ptr);
free(ptr);
ptr = NULL;
}
}
8. 局部变量未赋初始值
char *ptr;
if (ptr)
{
strcpy(ptr, "hello");
}
未完待续。。。