$ cat main.c
#include <stdio.h>
#include <malloc.h>
#define initsize 10
struct list{
int *data;
int maxsize;
int length;
};
//初始化顺序表
void Init_List(struct list *SeqList)
{
SeqList->data = (int *)malloc(sizeof(int)*initsize);
if(SeqList->data)
{
SeqList->length = 0;
SeqList->maxsize = initsize;
int i;
for(i = 0; i < SeqList->maxsize; i++)
SeqList->data[i] = 0;
}
}
//将顺序表填满
void Insert_Data(struct list *SeqList)
{
int i;
for(i = 0; i < SeqList->maxsize; i++)
SeqList->data[i] = 1;
SeqList->length = SeqList->maxsize;
}
//给顺序表扩容
struct list *Increase_space(struct list *SeqList, int len)
{
int i;
//重新开辟堆空间
struct list *new_SeqList = NULL;
printf("%d\n", __LINE__);
new_SeqList->data = (int *)malloc(sizeof(int)*(SeqList->maxsize + len));
new_SeqList->maxsize = SeqList->maxsize + len;
new_SeqList->length = SeqList->maxsize;
for(i = 0; i < new_SeqList->length; i++)
new_SeqList->data[i] = SeqList->data[i];
//释放掉原堆空间
free(SeqList->data);
}
//打印顺序表中的数据
void print_SeqList(struct list *SeqList)
{
int i;
for(i = 0; i < SeqList->length; i++)
printf("%d\n", SeqList->data[i]);
}
int main()
{
struct list SeqList;
Init_List(&SeqList);
Insert_Data(&SeqList);
struct list *new_SeqList = Increase_space(&SeqList, 5);
print_SeqList(new_SeqList);
return 0;
}
$ gcc-debug -o main main.c
main.c: In function ‘Increase_space’:
main.c:49:1: warning: control reaches end of non-void function [-Wreturn-type]
49 | }
| ^
$ ./main
41
main.c:42:27: runtime error: member access within null pointer of type 'struct list'
AddressSanitizer:DEADLYSIGNAL
=================================================================
==31965==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x561b6d9cf9a1 bp 0x7ffc485f7b20 sp 0x7ffc485f7ae0 T0)
==31965==The signal is caused by a WRITE memory access.
==31965==Hint: address points to the zero page.
#0 0x561b6d9cf9a1 in Increase_space /tmp/main.c:42
#1 0x561b6d9d0134 in main /tmp/main.c:64
#2 0x7f334644c30f in __libc_start_call_main (/usr/lib/libc.so.6+0x2d30f)
#3 0x7f334644c3c0 in __libc_start_main@GLIBC_2.2.5 (/usr/lib/libc.so.6+0x2d3c0)
#4 0x561b6d9cf154 in _start (/tmp/main+0x3154)
AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV /tmp/main.c:42 in Increase_space
==31965==ABORTING
$
|