错误出现在这一句:ST->elem = (ElemType*)malloc(sizeof(ElemType));
#include <stdio.h>
#define ERROR -1
#define SUCCEED 0
//#define EQ(a,b) (!strcmp((a),(b)))
typedef int KeyType;
typedef struct
{
char stu_id[15];
char name[20];
char Chinese[5];
char math[5];
char English[5];
}ElemType;
typedef struct
{
ElemType *elem;
int length;
}SSTable;
int Create(SSTable *ST, int n)
{
ST->elem = (ElemType*)malloc(sizeof(ElemType)); //错误点
if (NULL == ST->elem)
{
return ERROR;
}
else
{
return SUCCEED;
}
return 0;
}
int main(void)
{
SSTable *ST;
Create(ST,5);
//printf("%s",ST->elem->stu_id);
printf("HELLO\n");
return 0;
}
#include <stdio.h>
#define ERROR -1
#define SUCCEED 0
//#define EQ(a,b) (!strcmp((a),(b)))
typedef int KeyType;
typedef struct
{
char stu_id[15];
char name[20];
char Chinese[5];
char math[5];
char English[5];
}ElemType;
typedef struct
{
ElemType *elem;
int length;
}SSTable;
int Create(SSTable *ST, int n)
{
ST->elem = (ElemType*)malloc(sizeof(ElemType)); //错误点
if (NULL == ST->elem)
{
return ERROR;
}
else
{
return SUCCEED;
}
return 0;
}
int main(void)
{
SSTable *ST;
Create(ST,5);
//printf("%s",ST->elem->stu_id);
printf("HELLO\n");
return 0;
}
这是我在论坛上看到别人发的一个段错误的求助贴,我随便看了下,也没有发现问题,
但是看得出这段代码写得很规范,//#define EQ(a,b) (!strcmp((a),(b)))这一句
中对宏参数所加的括号,if (NULL == ST->elem)这一句中,将比较的常量放在前面,
都是些值得注意的地方。
主要来看看这段代码为什么出错,SSTable *ST;定义了一个指针,Create(ST,5)
这个出错了,ST->elem = (ElemType*)malloc(sizeof(ElemType));这句是对ST的一个
指针元素开辟空间,我们都知道,在指针使用前,都应该有具体的指向,因为指针仅仅是存放
的是一个地址,这个地址指向哪里,我们才能使用那里,而在使用ST以前,ST是没有指向的。
为什么这个很明显的错误隐藏了,可能是使用了指针嵌套,让我们忽略了外层指针的指向。
牢记:任何指针在使用前,都应该有指向,特别注意指针嵌套时。