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

C语言乘法表练习内存分配超标问题求助

C语言乘法表练习内存分配优化问题

我正在完成一门课程的C语言乘法表风格练习,代码功能完整,但自动测试显示当参数a=2、b=9、c=11、d=17时,实际分配了416字节内存,而预期仅需376字节。已用Valgrind开启所有细节运行代码,但未获得有效排查线索。尝试将表头生成逻辑整合进主乘法表创建流程后,内存占用比当前方案更高。destroyTimes函数应该不存在问题,因为Valgrind未报告内存泄漏。

times.c 代码

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

Times* createTimes(uint a, uint b, uint c, uint d) {
  int i,j;
  int rows=d-c+2;
  int cols=b-a+2;
  
  Times* ret = malloc(sizeof(Times));
  uint** kert = malloc(sizeof(uint*)*rows);

  if (!ret) {
    return NULL;
  }

  ret->a=a;
  ret->b=b;
  ret->c=c;
  ret->d=d;

  kert[0] = malloc(sizeof(uint)*(cols+1)); 
  kert[0][0] = 1;

  for(j=1;j<cols;j++) {
    kert[0][j] = a;
    a++;
  }
  a = ret->a;

  for(i=1;i<rows;i++) {
    kert[i] = malloc(sizeof(uint)*(cols+1));
    for(j=0;j<cols;j++) {
      kert[i][j] = c*kert[0][j];
    }
    c++;
  };

  ret->times = kert;

  return ret;
}

void destroyTimes(Times* kt) {
  uint i;
  uint rows = kt->d - kt->c + 2;
  if (kt == NULL) {
      return;  
  }

  for (i = 0; i < rows; i++) {
      free(kt->times[i]);
  }
  free(kt->times);

  free(kt);
}

times.h 代码

#ifndef TIMES_H
#define TIMES_H

typedef unsigned int uint;

struct Times {
  uint a,b,c,d;
  uint** times;
};

typedef struct Times Times;

Times* createTimes(uint,uint,uint,uint);

void destroyTimes(Times*);

#endif

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 14:53:11