C语言malloc函数分配内存总引用不可以被"read"或"written"的内存,如下

如下,编译可以过,运行不行,说内存不能为"read"或"written"
#include <stdio.h>
#include <stdlib.h>

struct link{
int n;
struct link* next;
};

struct link* create(void);

void main(){
struct link *head=create();
printf("Haha");
}

struct link* create(void){
struct link *head=NULL,*newlink,*tail;
int n=-1;
while(1){
printf("input the element:");
scanf("%d",&n);
if(n!=-1){
newlink=(struct link*)malloc(sizeof(struct link));
newlink->n=n;
if(head==NULL){
head->next=newlink;
head=tail=newlink;
return head;
}else{
tail->next=newlink;
return head;
}
}else{
return head;
}
}
}

如果知道怎么改的请说明下原理,谢谢

struct link* create(void)
{
struct link *head=NULL,*newlink,*tail;

head = (link *)malloc(sizeof(link));
tail = (link *)malloc(sizeof(link));

int n=-1;
while(1)
{
// 代码.....
// 没有空间,怎么能赋值
// head->next=newlink;
// head=tail=newlink;
}
free(head);
free(tail);
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2012-06-11
怎么看起来这么乱啊,你写的是单链表吗?
相似回答