malloc的突然失效 [英] malloc fails catastrophically

查看:148
本文介绍了malloc的突然失效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个队列C.从Java和其它托管语言的到来,我真的内存管理挣扎。这里是排队()功能:

I am trying to implement a Queue in C. Coming from Java and other managed languages, I am really struggling with memory management. Here is the enqueue() function:

int enqueue(Queue q, int value) {

    Node newNode = malloc(sizeof(Node));
    /*newNode->value = value;

    if (q->size == 0)
        q->head = newNode;
    else
        q->head->next = &newNode;

    q->size++;*/
}

我得到这个错误:

I am getting this error :

malloc.c:3096: sYSMALLOc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed.

FWIW,这里的code的其余部分(这是甚至对不对?):

FWIW, here's the rest of the code (is this even right?):

typedef struct NodeStruct *Node;
struct NodeStruct {
    Node* prev;
    Node* next;
    int value;
};

typedef struct QueueStruct *Queue;
struct QueueStruct {
    Node* head;
    Node* tail;
    int size;
    int capacity;
};

Queue newQueue(int size) {
    Queue q = malloc(sizeof(Queue));

    q->capacity = size;
    q->size = 0;
    q->head = NULL;
    q->tail = NULL;

    return q;
}

void printQueue(Queue q) {
    printf("Queue of size %d, capacity %d", q->size, q->capacity);
}    

int main() {
    Queue myQ = newQueue(10);

    // this seems to work
    printQueue(myQ);
    // epic fail
    enqueue(myQ, 5);

    return 0;
}

为什么会出现这种情况?

Why is this happening?

推荐答案

下面的行可能给你的悲伤:

The following line is probably giving you grief:

Node newNode = malloc(sizeof(Node));

节点为指针类型,所以你只分配足够的空间容纳一个指针,而不是一个完整的 NodeStruct 。我想你想要做的是:

Node is a pointer type, so you're only allocating enough space to hold a pointer, not an entire NodeStruct. I think what you want to do is:

Node newNode = malloc(sizeof(*newNode));

Node newNode = malloc(sizeof(NodeStruct));

存在同样的问题队列,你只分配了空间容纳一个指针,而不是一个 QueueStruct 。别的,我只是刚刚注意到,就是在你的 NodeStruct QueueStruct ,您使用的类型节点* ,这实际上是 NodeStruct ** ,这可能不是你想要的,因为节点已经是一个指针。

The same issue exists for Queue, you're only allocated space to hold a pointer, not a QueueStruct. Something else that I only just noticed, is that in your NodeStruct and QueueStruct, you are using the type Node*, which is actually NodeStruct **, which is probably not what you want, since Node is already a pointer.

这篇关于malloc的突然失效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆