C 创建空栈时出错

标签 c stack malloc

我正在尝试创建一个空堆栈,但不知何故 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/

相关文章:

c++ - 我怎样才能确保内存映射文件保持内存页面可访问?

c - 为什么更大的堆栈会使 .bss 增加 4 倍?

windows - 64 位大型 malloc

C:动态数组和指针数组创建段错误

c - 为什么不会发生段错误?

c - fread() 根据管道集错误从描述符读取,而不是没有数据的 EOF

c - (10%2) 是什么意思?

c - 使用 SSE 在 __m128i vector 中获取最大值?

java - 堆栈数据结构中索引越界异常

java - 创建一个包含 10 个整数元素的堆栈,然后使用函数添加一个元素