下面是我学习linux环境中c语言的程序,但是运行后提示说‘段错误’,请大家看看,谢谢了

dsdc 2006-12-21 11:15:23
下面是我学习linux环境中c语言的程序,但是运行后提示说‘段错误’,请大家看看,谢谢了
/*
programe: oplist.c
comment : operate stack,include:
1.create new node;
2.push a node;
3.pop a node;
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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,%d\n",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("%s\n",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;j<1025;j++)
{
strcpy(buf,"list21234567890.c");
node = createnode(buf);
push(&head,&node);
}
free(buf);
printf("display info:\n");
node = pop(&head);
while (node != NULL)
{
printf("%s\n",node->f_name);
free(node);
node = pop(&head);
}
printf("pop over.\n");
}
...全文
329 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
seayea 2006-12-26
  • 打赏
  • 举报
回复
info = (struct finfo*)malloc(sizeof(info));
if (info != NULL)
{
info->next = NULL;
strcpy(info->f_name,buf);
//printf("%s,",info->f_name);
//printf("%d,%d\n",strlen(buf),strlen(info->f_name));
return info;
}


info只是一个指针,还没有指向具体的struct,struct空间没有分配。此时往里面strcpy
访问了非法内存,所以段错误。

编程规范:局部变量要初始化;参数要校验。
hellojacky 2006-12-22
  • 打赏
  • 举报
回复
info = (struct finfo*)malloc(sizeof(info));
改成:
info = (struct finfo*)malloc(sizeof(struct finfo));
gongxuanjrj 2006-12-22
  • 打赏
  • 举报
回复
这个问题我在LINUX下做开发的时候也遇到过,段错误一般都是对内存的不正确访问造成的,可以用GDB调试一下,代码量不大的情况下,仔细检查一下,会很快发现问题所在
awjx 2006-12-21
  • 打赏
  • 举报
回复
用GDB调试一下,看看在哪里出错了。
darkone 2006-12-21
  • 打赏
  • 举报
回复
段错误 一般是内存非法访问,直接定义 char buf[50]; 没必要用buf = (char*)malloc(50*sizeof(char));
Andrionda 2006-12-21
  • 打赏
  • 举报
回复
for (j=1;j<1025;j++)
{
memset(buf,0,sizeof(char)*50);
strcpy(buf,"list21234567890.c");
node = createnode(buf);
push(&head,&node);
}

23,120

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧