首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 操作系统 > UNIXLINUX >

linux C编程出了“段异常” !

2012-02-03 
linux C编程出了“段错误” !!!一个线性链表的初始化程序,运行时显示“Segmentation fault ,代码如下:# incl

linux C编程出了“段错误” !!!
一个线性链表的初始化程序,运行时显示“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");
}

[解决办法]
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");
}

热点排行