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

如何计算C函数内存占用?求适配空闲内存的文件读取算法文档

内存计算疑问与动态内存读取算法需求

以下是我实现的load_dataset函数,用于读取文件数据,目前在计算该函数的内存占用时存在疑问:

struct point *load_dataset(char *filename, int dimension, int chunk_size, int start_idx) {

    struct point *dataset = malloc(chunk_size * sizeof(struct point));

    if(dataset == NULL){
        printf("Something went wrong in load_dataset(), memory allocation failed!");
        exit(1);
    }

    for (int i = 0; i < chunk_size; i++) {
        dataset[i].values = malloc(dimension * sizeof(double));
        if(dataset[i].values == NULL){
            printf("Something went wrong in load_dataset(), memory allocation failed!");
            exit(1);
        }
    }

    FILE *file;
    file=fopen(filename, "r");
    if (file == NULL){
        printf("Something went wrong in load_dataset(), file opening failed! (row 162)");
        exit(1);
    }

    char *line = NULL, *token;
    size_t len = 0;
    int i = start_idx - 1 ;
    int j = 0;
    bool end = true;

    while ((getline(&line, &len, file)) != -1 && i < chunk_size + start_idx) {
        if(i != - 1) {
            end = false;
            printf("line* size: %lu\n", sizeof(*line));
            while ((token = strsep(&line, ",")) != NULL) {
                printf("token* size: %lu\n", sizeof(*token));
                if(j == 0)
                    dataset[i].id = atoi(token);
                else
                    dataset[i].values[j-1] = atof(token);
                j++;
            }
            j = 0;
            i++;
        } else{
            i++;
        }
    }

    fclose(file);

    if (!end)
        return dataset;
    return NULL;
}

我列出了fclose()执行前的内存计算项:

  • 函数参数:sizeof(char*) + 3*sizeof(int)(对应char *filename、int dimension、int chunk_size、int start_idx)
  • struct point *dataset分配的内存:sizeof(struct point*) + chunk_size*sizeof(struct point)
  • FILE *file相关内存:sizeof(FILE*) + sizeof(FILE)
  • 局部变量:2*sizeof(char*) + sizeof(size_t) + 2*sizeof(int) + sizeof(bool)(对应char *line、char *token、size_t len、int i、int j、bool end)

疑问点

  1. char*类型参数及指针的内存计算方式是否正确?
  2. FILE *file的内存计算是否准确?

额外需求

需要编写可根据主存空闲量动态读取对应点数的算法,请求提供相关文档参考。

内容的提问来源于stack exchange,提问作者Luca Marchio

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 23:30:49