C Realloc 错误 - “断言 `ptr == alloc_last_block”失败了!”
我正在用 C 编写一个函数,它接受一个链表和一个谓词,并返回一个包含链表中满足此条件的所有值的数组。函数如下:
void **get_all_that(list_t *l, int (*pred)(const void *)) {
void **vals = NULL;
int i = 0; // Number of matches found
const size_t vps = sizeof(void *);
node_t *n = l->first;
while (n) {
if (pred(n->value)) {
vals = (void **)realloc(vals, i*vps); // (*)
vals[i] = n->value;
i++;
}
n = n->next;
}
if (vals != NULL) {
vals = (void **)realloc(vals, i*vps);
vals[i] = NULL; // NULL-terminate array
}
return vals;
}
我传入了一个始终返回 1 的谓词(即 get_all_that 基本上是 to_array),并且我在 i=4 的迭代中的星号行处收到错误。回溯上的错误(从 SIGABRT 自动打印)是“*** glibc detectors *** ~/list/test: realloc(): invalid next size: 0x0804c0e8 ***”
我打开 GDB 告诉它当 i=4 时,在调用 realloc 之前立即中断。然后,我尝试从 GDB 手动调用 realloc(vals, i*vps) 并收到错误消息:“ld.so: dl-minimal.c: 138: realloc: 断言 `ptr == alloc_last_block' 检测到不一致! “
有人知道发生了什么事吗?
I'm writing a function in C that takes in a linked list and a predicate and returns an array containing all values of the linked list satisfying this condition. Here's the function:
void **get_all_that(list_t *l, int (*pred)(const void *)) {
void **vals = NULL;
int i = 0; // Number of matches found
const size_t vps = sizeof(void *);
node_t *n = l->first;
while (n) {
if (pred(n->value)) {
vals = (void **)realloc(vals, i*vps); // (*)
vals[i] = n->value;
i++;
}
n = n->next;
}
if (vals != NULL) {
vals = (void **)realloc(vals, i*vps);
vals[i] = NULL; // NULL-terminate array
}
return vals;
}
I passed in a predicate that returns 1 always (i.e. get_all_that is basically to_array), and I'm getting an error at the starred line on the iteration where i=4. The error on the backtrace (which was automatically printed from a SIGABRT) is "*** glibc detected *** ~/list/test: realloc(): invalid next size: 0x0804c0e8 ***"
I opened up GDB telling it to break right before calling realloc when i=4. I then tried calling realloc(vals, i*vps) manually from GDB and got the error message: "Inconsistency detected by ld.so: dl-minimal.c: 138: realloc: Assertion `ptr == alloc_last_block' failed!
"
Anyone know what's going on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
realloc
分配的元素太少。尝试用i+1
替换i
。在替换传递给它的指针之前,您还应该检查 realloc 是否失败,否则您将遇到内存泄漏(更不用说崩溃了,因为您无法检查 NULL >) 失败时,从realloc
的返回值中删除不必要的和丑陋的转换也很好。Your
realloc
is allocating one too few elements. Try replacingi
byi+1
. You should also check for failure ofrealloc
before replacing the pointer you passed to it, since otherwise you will get a memory leak (not to mention crash since you fail to check forNULL
) on failure, and removing the unnecessary and ugly casts from the return value ofrealloc
would be nice too.你的第一个
realloc
调用长度为0,这是一个free
。因此,放置i+1
的建议尤为重要。And your first
realloc
calls the length with 0, which is afree
. So the advice to puti+1
is doubly important.