gpt4 book ai didi

C: Malloc 断言失败

转载 作者:行者123 更新时间:2023-11-30 19:33:19 25 4
gpt4 key购买 nike

我最近开始学习 C 并正在编写一些应用程序,我遇到了这个我以前从未见过的错误,并且显然是在我进行 malloc 时遇到的错误

malloc.c:2394: 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 (core dumped)

这是代码片段

typedef struct {
Node *root;
pthread_id id;
pid_t tid;
}Thread;

typedef struct {
Thread **thread;
int cap, len;
}arr;

static __thread Thread *self = NULL;
pthread_mutex_t lock;
static arr p;

static void
foo (void)
{
pthread_mutex_lock(&lock);
Thread **newthread;
if (p.len == p.cap){
if (p.cap != 0){
newthread = (Thread **) realloc(p.thread, (1+p.cap)*sizeof(Thread *));
}
else {
newthread = (Thread **)malloc(sizeof(Thread *));
}
if (!newthread){
printf("appendThreadpointer: Error while allocating size\n");
exit(1);
}
p.thread=newthread;
++p.cap;
}

++p.len;
Thread *t = malloc(sizeof(Thread *));
t->tid = syscall(SYS_gettid);
t->root = newNode();
t->id = pthread_self();
p.thread[p.len-1] = t;
self = t;
pthread_mutex_unlock(&lock);
}

谁能看出发生这种情况的原因吗?最奇怪的是如果我删除 tid来自 Thread 的字段struct 然后它工作正常,当我包含 tid 时它只会给我这个错误 field 。

我很困惑,对此的任何帮助将不胜感激,谢谢。

最佳答案

Thread *t = malloc(sizeof(Thread *)); 

可能应该改为

Thread *t = malloc(sizeof(Thread));

关于C: Malloc 断言失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46020556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com