如何为结构表编写自己的 realloc?

问题描述 投票:0回答:2

我正在写一个更大的项目,我在重新分配数组时遇到了问题。首先我尝试使用函数

realloc
,但它留下了内存泄漏和错误(该项目必须与Valgrind 兼容)。然后我尝试写自己的
realloc
,但它不起作用,我不知道为什么。请帮忙(我正在重新分配一个结构表)。

typedef struct {
    char w[2]; //word
    int v; //value
    int d; //direction
    char b; //binary
}node_t;

int realoc(node_t *huff, int length, int expand_size){
    node_t *temp = malloc((length+expand_size) * sizeof(node_t));
    for(int i=0; i<length ;i++){
        for(int j=0;j<2;j++)
            temp[i].w[j] = huff[i].w[j];
        temp[i].v = huff[i].v;
        temp[i].d = huff[i].d;
        temp[i].b = huff[i].b;
        huff=temp;
    }
    return length+expand_size
}
c structure realloc
2个回答
0
投票

指针

node_t *huff
指向的之前动态分配的内存没有被释放

也不要将您的函数命名为 C 标准函数。

例如,您可以使用标准 C 函数编写

realloc

node_t *temp = realloc( buff, (length+expand_size) * sizeof(node_t));

if ( temp != NULL ) buff = temp;

0
投票
  1. 不要只返回int
    node_t *
  2. 你的函数不会工作,因为它不修改指针
    huff
    所以它肯定会导致内存泄漏和无效的指针访问。
  3. 您的函数不会释放先前分配的内存。

总的来说,你写的功能差得离谱

node_t *node_t_realloc(node_t *huff, size_t newsize)
{
    node_t *temp = realloc(huff, sizeof(*temp) * newsize);
    return temp;
}


int main(void)
{
    node_t *myarray = NULL, *tmp;
    tmp = node_t_realloc(myarray, 1);
    if(tmp) myarray = tmp;
    tmp = node_t_realloc(myarray, 5);
    if(tmp) myarray = tmp;

    free(myarray);
}

或者如果您更喜欢副作用:

node_t *node_t_realloc(node_t **huff, size_t newsize)
{
    node_t *temp = realloc(*huff, sizeof(*temp) * newsize);
    if(temp) *huff = temp;
    return temp;
}


int main(void)
{
    node_t *myarray = NULL;
    node_t_realloc(&myarray, 1);
    node_t_realloc(&myarray, 5);

    free(myarray);
}
© www.soinside.com 2019 - 2024. All rights reserved.