目录

malloc、calloc、realloc在开辟/调整 空间失败的时候,返回NULL
如果在使用以上函数后没有进行是否是空指针的判断,很有可能会导致解引用空指针。
- int main()
- {
- int *p = (int*)malloc(10 * sizeof(int));
- int i = 0;
- for (i = 0; i <10; i++)
- {
- *(p + i) = i;
- }
-
- for (i = 0;i < 10; i++)
- {
- printf("%d",p[i]);
- return 0;
- }
-
- return 0;
- }
没有进行判断释放返回的地址是否是空指针NULL,然后直接使用解引用,而这样很有可能操作失误
- int main()
- {
- int *p = (int*)malloc(10 * sizeof(int));
- if (p == NULL)
- {
- perror("malloc");
- return 1;
- }
- int i = 0;
- for (i = 0; i <10; i++)
- {
- *(p + i) = i;
- }
-
- for (i = 0;i < 10; i++)
- {
- printf("%d",p[i]);
- return 0;
- }
-
- return 0;
- }
如果不进行判断,编译器也会发出警告


20个字节,在赋值时变成了20个元素,导致越界访问,最后会导致程序崩溃。

不过编译器在过程中并没有报错
- void test()
- {
- int a = 10;
- int *p = &a;
- free(p);
- }
运行后程序会崩溃


- void test()
- {
- int *p = (int *)malloc(100);
- p++;
- free(p);//p不再指向动态内存的起始位置
- }
现在的p指向的不是起始位置,而释放申请的空间一定是从起始位置开始释放的
- void test()
- {
- int *p = (int *)malloc(100);
- free(p);
- free(p);//重复释放
- }

多次释放也会崩溃
在free(p)后立马输入p=NULL就算多次释放也没有问题
- void test()
- {
- int *p = (int *)malloc(100);
- free(p);
- p = NULL;
- free(p);//重复释放
- }
- void test()
- {
- int *p = (int *)malloc(100);
- if(NULL != p)
- {
- *p = 20;
- }
- }
- int main()
- {
- test();
- while(1);
- }