当前位置: 技术问答>linux和unix
下面是我学习linux环境中c语言的程序,但是运行后提示说‘段错误’,请大家看看,谢谢了
来源: 互联网 发布时间:2015-12-31
本文导语: 下面是我学习linux环境中c语言的程序,但是运行后提示说‘段错误’,请大家看看,谢谢了 /* programe: oplist.c comment : operate stack,include: 1.create new node; 2.push a node; 3.pop ...
下面是我学习linux环境中c语言的程序,但是运行后提示说‘段错误’,请大家看看,谢谢了
/*
programe: oplist.c
comment : operate stack,include:
1.create new node;
2.push a node;
3.pop a node;
*/
#include
#include
#include
struct finfo
{
char f_name[1024];
struct finfo *next;
};
struct finfo *createnode(char *buf)
{
struct finfo *info;
int i;
info = (struct finfo*)malloc(sizeof(info));
if (info != NULL)
{
info->next = NULL;
strcpy(info->f_name,buf);
//printf("%s,",info->f_name);
//printf("%d,%dn",strlen(buf),strlen(info->f_name));
return info;
}
else
return NULL;
}
void push(struct finfo **head,struct finfo **node)
{
if (head == NULL)
{
*head = *node;
(*head)->next = NULL;
}
else
{
(*node)->next = *head;
*head = *node;
}
}
struct finfo *pop(struct finfo **head)
{
struct finfo *tmp;
if (*head == NULL)
return NULL;
else
{
tmp = *head;
*head = tmp->next;
//printf("%sn",tmp->f_name);
return tmp;
}
}
main()
{
char *buf;
struct finfo *head;
struct finfo *node;
head = NULL;
node = NULL;
int j;
buf = (char*)malloc(50*sizeof(char));
printf("ready to copy.");
for (j=1;jf_name);
free(node);
node = pop(&head);
}
printf("pop over.n");
}
/*
programe: oplist.c
comment : operate stack,include:
1.create new node;
2.push a node;
3.pop a node;
*/
#include
#include
#include
struct finfo
{
char f_name[1024];
struct finfo *next;
};
struct finfo *createnode(char *buf)
{
struct finfo *info;
int i;
info = (struct finfo*)malloc(sizeof(info));
if (info != NULL)
{
info->next = NULL;
strcpy(info->f_name,buf);
//printf("%s,",info->f_name);
//printf("%d,%dn",strlen(buf),strlen(info->f_name));
return info;
}
else
return NULL;
}
void push(struct finfo **head,struct finfo **node)
{
if (head == NULL)
{
*head = *node;
(*head)->next = NULL;
}
else
{
(*node)->next = *head;
*head = *node;
}
}
struct finfo *pop(struct finfo **head)
{
struct finfo *tmp;
if (*head == NULL)
return NULL;
else
{
tmp = *head;
*head = tmp->next;
//printf("%sn",tmp->f_name);
return tmp;
}
}
main()
{
char *buf;
struct finfo *head;
struct finfo *node;
head = NULL;
node = NULL;
int j;
buf = (char*)malloc(50*sizeof(char));
printf("ready to copy.");
for (j=1;jf_name);
free(node);
node = pop(&head);
}
printf("pop over.n");
}
|
info = (struct finfo*)malloc(sizeof(info));
if (info != NULL)
{
info->next = NULL;
strcpy(info->f_name,buf);
//printf("%s,",info->f_name);
//printf("%d,%dn",strlen(buf),strlen(info->f_name));
return info;
}
info只是一个指针,还没有指向具体的struct,struct空间没有分配。此时往里面strcpy
访问了非法内存,所以段错误。
编程规范:局部变量要初始化;参数要校验。
if (info != NULL)
{
info->next = NULL;
strcpy(info->f_name,buf);
//printf("%s,",info->f_name);
//printf("%d,%dn",strlen(buf),strlen(info->f_name));
return info;
}
info只是一个指针,还没有指向具体的struct,struct空间没有分配。此时往里面strcpy
访问了非法内存,所以段错误。
编程规范:局部变量要初始化;参数要校验。
|
用GDB调试一下,看看在哪里出错了。
|
for (j=1;j