我正在尝试创建一个空堆栈,但不知何故 malloc 出现错误,即使使用调试器我也无法弄清楚。
我的调试器显示的消息是:
sysmalloc: Assertion (old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0) failed.
Aborted
我该如何解决?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
typedef struct
{
int x;
int y;
int r;
int g;
int b;
}Pixel;
typedef int TypeKey;
typedef struct {
TypeKey Key;
Pixel P;
} TypeItem;
typedef struct Cell_str *Pointer;
typedef struct Cell_str {
TypeItem Item;
Pointer Next;
} Cell;
typedef struct {
Pointer Top, Bottom;
int Size;
} TypeStack;
void FEmpty(TypeStack *Stack)
{
Stack->Top = (Pointer)malloc(sizeof(Cell*));
Stack->Bottom = Stack->Top;
Stack->Top->Next = NULL;
Stack->Size = 0;
}
int Empty(const TypeStack *Stack){
return (Stack->Top == Stack->Bottom);
}
int size(TypeStack Stack)
{
return (Stack.Size) ;
}
int main(int argc, char *argv[])
{
Pixel P[500][500];;
TypeStack *Stack;
FEmpty(Stack);
return 0;
}
最佳答案
1
TypeStack *Stack;
FEmpty(Stack);
Stack
未初始化 - 它指向任何内容或垃圾。
在 FEmpty
中,您会立即取消引用(无效的)指针,从而导致未定义的行为。
您需要使用malloc
分配结构,或者简单地声明一个局部变量:
TypeStack Stack;
FEmpty(&Stack);
2
Stack->Top = (Pointer)malloc(sizeof(Cell*));
接下来,你没有在这里分配足够的内存。您只是在分配指针本身 的大小,而不是它指向的结构。
使用这个构造来避免这个错误。 And don't cast the result of malloc
.
Stack->Top = malloc(sizeof(*Stack->Top));
关于C 创建空栈时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50093220/