![](/img/trans.png)
[英]Why does "malloc(): corrupted top size" error get fixed when I have printf() before/after it?
[英]Could someone help me figure out why I am getting the error malloc(): corrupted top size
我目前正在嘗試創建一個動態擴展數組,我可以在 c++ 和 c 中使用該數組,該數組包含在我稱為Train
的結構中,該結構必須使用名為initialize_train
的 function 進行初始化,並且添加了更多內容使用insert_cart
到數組,當執行此 function 時,它使用 function realloc
將數組擴展一個,然后通過指針插入分配的數組。 當我第二次使用 function malloc
時,我遇到的問題是insert_cart
,錯誤是malloc(): corrupted top size 。 我已經嘗試弄清楚為什么會發生這種情況 2 天,但為什么它似乎只是在我第三次使用 malloc 時發生,而第 0 行和第 51 行的代碼保持不變。
#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
我期待 output 是
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
你有多個問題。
讓我們從循環開始while (*text != '\n')
用於復制字符串(而不是使用標准strcpy
)。 此循環將查找換行符以了解何時結束。
但是你傳遞給 function 的字符串沒有任何換行符,所以你的循環將 go 超出范圍並且你將有未定義的行為。
要么使用普通的strcpy
復制字符串:
strcpy(allocatedText, text);
或者循環直到到達字符串終止符:
while (*text != '\0')
另一個非常嚴重的問題是如何使用結構的count
成員。 您將它用作元素數量和memory 重新分配的字節大小。 不可能兩者兼而有之,只能是其中之一。
在發現更多錯誤后,這里列出了我目前能找到的所有錯誤:
allocatedText
的范圍allocatedText
train->count
作為realloc
調用的新字節大小,稍后您將其用作train->carts
數組的索引。 不能兩者兼而有之,只有一個或另一個free(&train)
試圖釋放 memory 不是由malloc
分配的所有這些問題都會以某種方式導致未定義的行為,並且可以解釋您的所有消息和未來的崩潰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.