日期:2014-05-16  浏览次数:20622 次

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");
}