malloc1
来源:互联网 发布:汤姆大叔 javascript 编辑:程序博客网 时间:2024/06/06 02:49
1.local variable 放在stack大小有限制 default 1Mb 但是又不想放在global
2.运行时候才知道memory大小
3.不需要的时候可以free
----------------
malloc 不保证成功 要检测return
离开一定要free
---------
aa(){
char s1[100];
char *s2=NULL;
s2 =(char*)malloc(100);
strcpy(s,"....");
free(s2);
}
void aa(){
char *s=NULL;
if((s=(char *)malloc(100))==NULL) //不保证一定成功
return;
strcpy(s, "...");
free(s);
s =NULL; //单线程可省略 多线程 一定要写 否则会double free
}
---------------------------------------------------------------------
calloc 跟malloc 基本一样 他还会initialize 每个byte 为0 好处就是清0 坏处 变慢 跟malloc一样 成功返回地址
失败返回 NULL
realloc 改变memory大小 通常是变大 成功可能是原本地皮直接扩大 也可能是一块新的地皮 失败return NULL
原来的memory还在
---------------------------------------------------------------
main(){
char *p1=NULL, *p2=NULL;
//要一块1000bytes
if((p1=(char*)malloc(10000))==NULL)
return;
//使用p1
//发现10000不够大,要改成20000
p2 = realloc(p1,20000);
if(p2 == NULL){ //没要到 继续使用p1 或者是放弃
}
else{ //如果有申请到的话 会自动帮你搬家
p1=p2; //继续使用p1
p2 = NULL;
}
free(p1); //还回去
p1 = NULL;
}
---------------------------------------------------------
performance:
calloc<malloc<realloc
buffer initialization
buffer reused
--------------------------------------------------------
struct node{
int data;
struct node *next
};
----------------------------------------------
struct node *ptr = head;
while(ptr!=NULL){
printf("%d\n", ptr->data);
ptr = ptr->next;
}
打印出每一个元素
---------------------------------------------
insert:
第一步(创建要加入的点)
struct node *p= NULL;
p = (struct node *) malloc(sizeof(struct node));
if (p==NULL) return;
p->data = 4;
p->next = NULL;
第二步:(找到最后一个位置)
struct node *ptr = head;
if(ptr == NULL){ //list本来就是空的
head = p;
return;
}
else{
while(ptr->next!=NULL)
ptr = ptr->next;
}
第三部:
p->next = ptr->next;
ptr->next=p;
--------------------------------------------
1.找到指定的data ptr2在ptr的前一个
struct node *ptr = head, *ptr2=NULL;
while(ptr!=NULL){
if(ptr->data == N)
break;
ptr2=ptr;
ptr=ptr->next;
}
-----------------------------------------------
2.删掉
if(ptr==NULL) return; //没找到
if(ptr==head)
head = head->next;
else
ptr2->next = ptr->next;
---------------------------------------------
3.free node
free(ptr);
ptr = NULL;
- malloc1
- python运维first_chapter
- You Don't Know JS: Types & Grammar 总结
- javascript学习记录(二)-function函数的应用之sort()函数详解
- 从零开始学_JavaScript_系列(55)——Generator函数(3)yield*表达式
- 响应式布局学习
- malloc1
- 从零开始学_JavaScript_系列(56)——Generator函数(4)简写,this与继承
- HDU 6166 Senior Pan [二分+SPFA]
- 《运营之光》-- 学习笔记(一)
- Hdu 4389 X mod f(x) 数位DP
- 从零开始学_JavaScript_系列(57)——Generator函数(5)状态机与函数的应用
- solr6.6.0安装部署至tomcat教程
- VS2010编写UDP网络通信程序的问题(借用孙鑫老师《深入VC++》书中程序)
- Pat(A) 1071. Speech Patterns (25)