提问人:joshua woulfe 提问时间:11/22/2022 最后编辑:joshua woulfe 更新时间:11/22/2022 访问量:76
有人可以帮我弄清楚为什么我收到错误malloc():损坏的顶部尺寸
Could someone help me figure out why I am getting the error malloc(): corrupted top size
问:
概述
我目前正在尝试创建一个能够在 c++ 和 c 中使用的动态扩展数组,该数组包含在我调用的结构中,该结构必须使用调用的函数进行初始化,并且使用调用的函数向数组添加更多,当执行此函数时,它使用该函数将数组扩展 1,然后通过指针插入分配的数组。当我第二次使用该函数时,我遇到的问题发生了,错误是 malloc():损坏的顶部大小。我试图弄清楚为什么会发生这种情况 2 天,但不知道为什么会发生这种情况,只是当第 0 行和第 51 行的代码保持不变时,它似乎发生在我第三次使用 malloc 时。Train
initialize_train
insert_cart
realloc
malloc
insert_cart
法典
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
const unsigned short CHAR_POINTER_SIZE = sizeof(char*);
typedef struct
{
char **carts;
unsigned short count;
} Train;
void initialize_train(Train *train)
{
train->carts = (char **)malloc(CHAR_POINTER_SIZE);
train->count = 0;
}
void insert_cart(Train *train, char *text)
{
char* allocatedText;
{
unsigned int length = strlen(text) + 1 ;
printf("%d: %s\n", length, text);
allocatedText = (char*)malloc(length);
printf("bytes allocated\n");
}
train->count += CHAR_POINTER_SIZE;
train->carts = (char **)realloc(train->carts, train->count);
unsigned int index = 0;
while (*text != '\n')
{
allocatedText[index] = *text;
text++;
index++;
}
train->carts[train->count++] = allocatedText;
}
int main(void)
{
Train train;
initialize_train(&train);
insert_cart(&train, "cart_0");
insert_cart(&train, "cart_1");
insert_cart(&train, "cart_2");
insert_cart(&train, "cart_3");
insert_cart(&train, "cart_4");
insert_cart(&train, "cart_5");
free(&train);
}
输出
7: cart_0
bytes allocated
7: cart_1
malloc(): corrupted top size
我期望输出是
7: cart_0
bytes allocated
7: cart_1
bytes allocated
7: cart_2
bytes allocated
7: cart_3
bytes allocated
7: cart_4
bytes allocated
7: cart_5
bytes allocated
答:
0赞
Some programmer dude
11/22/2022
#1
您有多个问题。
让我们从用于复制字符串的循环开始(而不是使用标准)。此循环将查找换行符以了解何时结束。while (*text != '\n')
strcpy
但是你传递给函数的字符串没有任何换行符,所以你的循环会越界,你将有未定义的行为。
使用 plain 复制字符串:strcpy
strcpy(allocatedText, text);
或者循环,直到你到达字符串终止符:
while (*text != '\0')
另一个非常严重的问题是如何使用结构的成员。您可以将其用作元素数和内存重新分配的字节大小。它不能两者兼而有之,只能是其中之一。count
在发现更多错误后,以下是我目前能找到的所有错误列表:
- 复制输入字符串的循环不会在 null 终止符上停止,从而超出输入字符串的边界。
- 由于前面的问题,你会写出越界的
allocatedText
- 从不以 null 结尾
allocatedText
- 用作调用的新字节大小,稍后将其用作数组的索引。它不能两者兼而有之,只能是其中之一
train->count
realloc
train->carts
- 调用 which 尝试释放未由
free(&train)
malloc
所有这些问题都会以一种或另一种方式导致未定义的行为,并可能解释您的所有消息和未来的崩溃。
评论
0赞
joshua woulfe
11/22/2022
谢谢!更改它“\0”也修复了错误,但现在它有错误munmap_chunk(): invalid pointer
0赞
Some programmer dude
11/22/2022
@joshuawoulfe这可能是我提到的另一个问题的原因。
0赞
joshua woulfe
11/22/2022
也许吧,但这只是在问题上贴上胶带,但从计数中减去 1 确实避免了错误。
0赞
Some programmer dude
11/22/2022
@joshuawoulfe 调用时,用作要重新分配的字节大小。稍后用作元素索引。不能两者兼而有之,你必须决定一个或另一个!realloc
count
count
0赞
joshua woulfe
11/22/2022
也不要认为问题只存在于“\n”上,因为如果我修改 while 循环以打印字符,它似乎会通过程序中存储的内容。结果是“cart_0cart_1cart_2cart_3cart_4cart_5D xh x ' j zRx”,并一直持续到命中 '\n'
上一个:动态分配的向量
下一个:文本文件转换为动态数组
评论