单链表法编写malloc运行时出现段错误,请教各位高手,帮忙查出错误!!!
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define max_size 10000
#define lb_size 12
#define arr_length 180
char start[max_size];
typedef struct link
{
size_t size;
int tag;
struct link *next;
}Link;
Link *lhead;
void init_lblock(Link **L)//单链表初始化
{
*L=(Link*)start;
(*L)->size=max_size-lb_size;
(*L)->tag=0;
(*L)->next=NULL;
}
void* m_malloc(size_t size)//自己写的malloc函数
{
Link *p=lhead;
Link *temp=NULL;
while(p)
{
if(p->tag==0 && p->size>=size+lb_size)
break;
else
p=p->next;
}
if(NULL==p)
return p;
if(p->size>size+lb_size)
{
Link *s;
s=(Link*)((char*)p+size+lb_size);
s->size=p->size-size-lb_size;
s->tag=0;
s->next=p->next;
p->next=s;
}
p->tag=1;
return p+1;
}
void m_free(void *ptr)//自己编写的free函数
{
Link *p=lhead;
if(ptr==p+1)
{
if(p->next->tag==0)
{
p->size+=p->next->size+lb_size;
p->next=p->next->next;
}
p->tag=0;
return;
}
while(p)
{
if(ptr==p->next+1)
break;
else
p=p->next;
}
if(p=NULL)return;
p->next->tag=0;
if(p->next->next->tag==0)
{
Link *q=p->next;
q->size+=q->next->size+lb_size;
q->next=q->next->next;
}
if(p->tag==0)
{
p->size+=p->next->size+lb_size;
p->next=p->next->next;
}
}
int main()
{
int i,index=0;
init_lblock(&lhead);
char*array[arr_length]={};
for(i=0;i<10000;i++)//循环一万次则算成功
{
printf("i=%d",i);
index=rand()%arr_length;
printf(",%d\t",index);
if(array[i]==NULL)
{
array[index]=(char*)m_malloc(20+rand()%100);//用自己编写的malloc分配空间
strcpy(array[index],"malloc is successful");
puts(array[index]);
}
else
{
m_free(array[index]);//使用自己编写的释放函数free
printf("free is ok\n");
array[index]=NULL;
}
}
return 0;
}