linux C编程出了“段错误” !!!

windwarrior 2010-04-26 08:17:35
一个线性链表的初始化程序,运行时显示“Segmentation fault" ,代码如下:
# include <stdio.h>
# include <malloc.h>
# include <stddef.h>
# include <stdlib.h>

# define TRUE 1
# define FALSE 0
# define OK 1
# define ERROR 0
# define OVERFLOW -1

struct sqlist
{
int * p;
int length;
int listsize;
}sqlist;

int Initlist_sq(struct sqlist * L, int LIST_INIT_SIZE)
{
L->p = (int * )malloc(LIST_INIT_SIZE * sizeof(int));
if ( L->p== NULL ) exit(OVERFLOW);
L->length = 0;
L->listsize = LIST_INIT_SIZE;
return OK;
}

void main()
{
struct sqlist * p;
int status = 0;
status = Initlist_sq(p, 100);
if( status)
printf("memory allocation succeed\n");
else
printf("memory allocation failed\n");
}
...全文
70 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
TANG_XIAO_BIN 2010-04-26
  • 打赏
  • 举报
回复
呵呵,这是因为你没有弄清楚,你分配的内存给了哪个变量,可能是一时迷糊!
windwarrior 2010-04-26
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 tang_xiao_bin 的回复:]
# include <stdio.h>
# include <malloc.h>
# include <stddef.h>
# include <stdlib.h>

# define TRUE 1
# define FALSE 0
# define OK 1
# define ERROR 0
# define OVERFLOW -1

struct sqlist
{
……
[/Quote]
谢了 没有理解清楚指针 给p初始化就好了
TANG_XIAO_BIN 2010-04-26
  • 打赏
  • 举报
回复
# include <stdio.h>
# include <malloc.h>
# include <stddef.h>
# include <stdlib.h>

# define TRUE 1
# define FALSE 0
# define OK 1
# define ERROR 0
# define OVERFLOW -1

struct sqlist
{
int * p;
int length;
int listsize;
}sqlist;

int Initlist_sq(struct sqlist * L, int LIST_INIT_SIZE)
{
L->p = (int * )malloc(LIST_INIT_SIZE * sizeof(int));//问题就在这里出现的
if ( L->p== NULL ) exit(OVERFLOW);
L->length = 0;
L->listsize = LIST_INIT_SIZE;
return OK;
}

void main()
{
struct sqlist * p = malloc(sizeof(sqlist));//你访问的地址是无效的
int status = 0;
status = Initlist_sq(p, 100);
if( status)
printf("memory allocation succeed\n");
else
printf("memory allocation failed\n");
}
windwarrior 2010-04-26
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 tang_xiao_bin 的回复:]
int Initlist_sq(struct sqlist * L, int LIST_INIT_SIZE)
{
L->p = (int * )malloc(LIST_INIT_SIZE * sizeof(int));//使用无效指针,你应该给L也分配内存
if ( L->p== NULL ) exit(OVERFLOW);
L->length = 0;
L->listsiz……
[/Quote]
你能稍微改一下吗 我新手 不好意思
TANG_XIAO_BIN 2010-04-26
  • 打赏
  • 举报
回复
int Initlist_sq(struct sqlist * L, int LIST_INIT_SIZE)
{
L->p = (int * )malloc(LIST_INIT_SIZE * sizeof(int));//使用无效指针,你应该给L也分配内存
if ( L->p== NULL ) exit(OVERFLOW);
L->length = 0;
L->listsize = LIST_INIT_SIZE;
return OK;
}

void main()
{
struct sqlist * p;//是无效指针
int status = 0;
status = Initlist_sq(p, 100);
if( status)
printf("memory allocation succeed\n");
else
printf("memory allocation failed\n");
}

23,125

社区成员

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

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