优化了命名

This commit is contained in:
lzy
2024-04-28 13:10:56 +08:00
parent d75a518c0f
commit ba9f2e37a7
155 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,115 @@
# 目录
- [目录](#目录)
- [动态内存管理](#动态内存管理)
- [函数传参相关问题](#函数传参相关问题)
- [关于 free](#关于-free)
# 动态内存管理
```` c
void *calloc(size_t nmemb, size_t size); // 分配n个size空间
void *malloc(size_t size); // 分配size空间
void free(void *ptr);
void *realloc(void *ptr, size_t size); // 重新分配空间
````
原则:谁申请谁释放。
## 函数传参相关问题
1. 要么用二级指针
2. 要么用返回值
```c
#include <stdio.h>
#include <stdlib.h>
// void func(int **p, int n)
// {
//     *p = malloc(n);
//     if (NULL == *p)
//         exit(1);
//     return;
// }
void *func(int *p, int n)
{
    p = malloc(n);
    if (NULL == p)
        exit(1);
    return p;
}
int main()
{
    int  num = 100;
    int *p   = NULL;
    // func(&p, num);
    p = func(p, num);
    free(p);
    exit(0);
}
```
## 关于 free
`free`操作没有扣掉那块内存,没有改变那块内存的值,也没有改变指针的指向。
仅仅是让这个指针不在有操作那块内存的权力,所以如果依旧用这个指针,可能不会报错,依旧可以操作那块内存。但是这就是野指针了,这是十分危险的。
比较好的习惯是在`free`之后马上给指针赋值`NULL`,这样后续再操作这个指针,就会报段错误。
```c
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *p = NULL;
    p = malloc(sizeof(int));
    if (NULL == p)
    {
        printf("malloc() error!\n");
        exit(1);
    }
    *p = 10;
    printf("%p-->%d\n", *p);
    free(p);
    p = NULL;   // !important
    printf("%p-->%d\n", *p);
    // 0x5a677368 -- > 1516729192
    *p = 123;
    printf("%p-->%d\n", *p);
    // 0x7b -- > 0
    exit(0);
}
```

View File

@@ -0,0 +1,24 @@
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p;
int num = 5;
p = malloc(sizeof(int) * num);
for (int i = 0; i < num; i++)
{
scanf("%d", &p[i]);
}
for (int i = 0; i < num; i++)
{
printf("%d ", p[i]);
}
printf("\n");
free(p);
exit(0);
}

View File

@@ -0,0 +1,30 @@
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p = NULL;
p = malloc(sizeof(int));
if (NULL == p)
{
printf("malloc() error!\n");
exit(1);
}
*p = 10;
printf("%p-->%d\n", *p);
free(p);
p = NULL; // !important
printf("%p-->%d\n", *p);
// 0x5a677368 -- > 1516729192
*p = 123;
printf("%p-->%d\n", *p);
// 0x7b -- > 0
exit(0);
}

View File

@@ -0,0 +1,36 @@
#include <stdio.h>
#include <stdlib.h>
// void func(int **p, int n)
// {
// *p = malloc(n);
// if (NULL == *p)
// exit(1);
// return;
// }
void *func(int *p, int n)
{
p = malloc(n);
if (NULL == p)
exit(1);
return p;
}
int main()
{
int num = 100;
int *p = NULL;
// func(&p, num);
p = func(p, num);
free(p);
exit(0);
}