gpt4 book ai didi

C - 某些尺寸的 "sysmalloc: Assertion ..."错误

转载 作者:太空宇宙 更新时间:2023-11-04 08:10:42 24 4
gpt4 key购买 nike

#include <stdlib.h>
#include <stdio.h>

char* text1 = "This is a string.";
char* text2 = "Yet another thing.";

void copyCodes (int* list, char* text){
while(*text != 0){
*list = *text;
list++;
text++;
}
*(list+sizeof(int)) = 0;
}

int main(void){
int size = 72; //THIS IS THE ERROR
int* list1 = malloc(size);
int* list2 = malloc(size);

copyCodes(list1, text1);
copyCodes(list2, text2);

free(list1);
free(list2);
}

上面的代码确实有效。
但是,如果我将 size 更改为 72 到 89 (不包括 72 和 89) 之间的任何值,我会得到一个 sysmalloc: Assertion ...错误。

为什么?

注意
我的 Ubuntu (16.04) 机器上出现错误,但它在我的 OSX (10.11.5) 机器上运行良好。

完全错误

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

编辑1
值得注意的是,该代码在用 MIPS 汇编语言编写并为每个数组分配 80 字节内存时有效。 (上面的 C 代码是汇编指令的精确翻译)。

最佳答案

那是因为当您在此处超出分配空间的末尾写入时,您调用了未定义的行为:

*(list+sizeof(int)) = 0;

对于 18 个字符的第二个字符串,list 递增 18 次,假设是 4 字节整数,现在指向分配的 72 字节末尾的 1。然后你做上面的,它写在偏移量 72 + sizeof(int) * sizeof(*list) == 72 + 16.

顺便说一句,“工作正常”只意味着“我很幸运地不知道什么错误正在等待发生”。

关于C - 某些尺寸的 "sysmalloc: Assertion ..."错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39772222/

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