You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言动态内存问题:函数内调用realloc触发未分配指针错误

解决C语言封装realloc到函数后出现的pointer being realloc'd was not allocated错误

问题根源:值传递导致指针未更新

C语言函数参数采用值传递,func中的client_details是主函数中指针的局部副本。当realloc返回新的内存地址时,函数内仅修改了这个副本的指向,主函数里的原始指针始终保持初始分配的旧地址。

第二次调用func时,程序会用已经被realloc释放的旧指针再次请求内存分配,这就触发了pointer being realloc'd was not allocated的错误。

额外隐藏问题:内存大小计算错误

你的两段代码中都存在一个潜在bug:sizeof(client_details)获取的是指针本身的大小(64位系统为8字节),而非struct client_detail结构体的大小。这会导致实际分配的内存远小于需求,后续访问结构体成员时会触发越界,只是第一个代码因为在主函数内覆盖了指针,暂时未暴露问题。正确的写法应该是sizeof(*client_details)。

修复方案

1. 使用双重指针传递指针变量

通过传递指针的指针(双重指针),让函数能直接修改主函数中指针的指向:

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

struct client_detail
{
    int id, fd;
};

struct group_member
{
    int id, fd, isAdmin;
};

struct group_detail
{
    int id, isBroadcastOnly, size;
    struct group_member members[5];
};

void func(struct client_detail **client_details, int *size){
    // 先用临时变量接收realloc结果,避免分配失败时丢失原指针
    struct client_detail *temp = realloc(*client_details, (*size + 1) * sizeof(**client_details));
    if (temp == NULL) {
        perror("realloc failed");
        exit(EXIT_FAILURE);
    }
    *client_details = temp;
    *size = *size + 1;
}

int main()
{
    struct group_detail *group_details = malloc(0 * sizeof(*group_details));
    struct client_detail *client_details = malloc(1 * sizeof(*client_details));
    int size = 0;
    int j = 0;
    while(j < 100){
        // 传递指针的地址
        func(&client_details, &size);
        j++;
    }
    // 记得释放内存
    free(client_details);
    free(group_details);
    return 0;
}

2. 关键修复点说明

  • 函数参数改为struct client_detail **client_details,接收主函数指针的地址
  • 用**client_details计算结构体大小,确保分配的内存符合需求
  • 用临时变量接收realloc的返回值,避免分配失败时原指针被覆盖导致内存泄漏
  • 主函数调用时传递&client_details,让函数能修改原始指针

内容的提问来源于stack exchange,提问作者Subham Jain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 10:20:36