【问题标题】:Could someone help me figure out why I am getting the error malloc(): corrupted top size有人可以帮我弄清楚为什么我收到错误 malloc(): corrupted top size
【发布时间】:2022-11-22 16:34:12
【问题描述】:

概述

我目前正在尝试创建一个可以在 C++ 和 C 中使用的动态扩展数组,该数组包含在我称为 Train 的结构中,必须使用名为 initialize_train 的函数对其进行初始化并使用insert_cart将更多内容添加到数组中,当执行此函数时,它使用函数realloc将数组扩展一,然后通过指针插入分配的数组。当我第二次使用函数malloc时,我遇到的问题是insert_cart,错误是malloc():损坏的顶部大小.我已经尝试弄清楚为什么会发生这种情况 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

我期待输出是

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

【问题讨论】:

    标签: c dynamic malloc realloc


    【解决方案1】:

    你有多个问题。

    让我们从你用来复制字符串的循环while (*text != ' ')开始(而不是使用标准的strcpy)。此循环将查找换行符以了解何时结束。

    但是你传递给函数的字符串没有任何换行符,所以你的循环将越界,你将有未定义的行为.

    要么使用普通的strcpy来复制字符串:

    strcpy(allocatedText, text);
    

    或者循环直到到达字符串终止符:

    while (*text != '
    猜你喜欢
    • 2022-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 2016-11-04
    • 2020-09-24
    相关资源
    最近更新 更多