【动态内存管理】 | 您所在的位置:网站首页 › 出省需要申请吗 › 【动态内存管理】 |
malloc free #include #include int main() { int* p = (int*)malloc(40); if (p == NULL) { perror("malloc"); return 1; } //开辟成功 int i = 0; for (i = 0; i //int* p = (int*)calloc(INT_MAX, sizeof(int)); int* p = (int*)calloc(10, sizeof(int)); //0 0 0 0 0 0 0 0 0 0 if (p == NULL) { perror("calloc"); return 1; } //打印数据 int i = 0; for (i = 0; i int* p = (int*)malloc(40); if (p == NULL) { perror("malloc"); return 1; } //初始化为1~10 int i = 0; for (i = 0; i p = ptr; ptr = NULL; } else { perror("realloc"); return 1; } //打印数据 for (i = 0; i int* p = (int*)malloc(40); *p = 20;//如果p的值是NULL,那么就会有问题 }对返回值进行检查 2、对动态开辟空间的越界访问 int main() { int* p = (int*)malloc(40); if (p == NULL) { perror("malloc"); return 1; } int i = 0; //对动态开辟空间的越界访问 for (i = 0; i int a = 10; int* p = &a; printf("%d\n", *p); // free(p); p = NULL; return 0; }4、使用free释放一块动态开辟内存的一部分 int main() { int* p = (int*)malloc(40); if (p == NULL) { perror("malloc"); return 1; } int i = 0; for (i = 0; i int* p = (int*)malloc(40); if (p == NULL) { return 1; } //使用 free(p); p = NULL; free(p); return 0; } free(p); 先去free p = NULL; 再去置为空6、动态开辟内存忘记释放(内存泄露) void test() { int* p = (int*)malloc(100); if (NULL != p) { *p = 20; } } int main() { test(); // while (1); return 0; } |
CopyRight 2018-2019 实验室设备网 版权所有 |