网页资讯视频图片知道文库贴吧地图采购
进入贴吧全吧搜索

 
 
 
日一二三四五六
       
       
       
       
       
       

签到排名:今日本吧第个签到,

本吧因你更精彩,明天继续来努力!

本吧签到人数:0

一键签到
成为超级会员,使用一键签到
一键签到
本月漏签0次!
0
成为超级会员,赠送8张补签卡
如何使用?
点击日历上漏签日期,即可进行补签。
连续签到:天  累计签到:天
0
超级会员单次开通12个月以上,赠送连续签到卡3张
使用连续签到卡
07月17日漏签0天
c语言吧 关注:798,838贴子:4,357,390
  • 看贴

  • 图片

  • 吧主推荐

  • 视频

  • 游戏

  • 11回复贴,共1页
<<返回c语言吧
>0< 加载中...

各位大佬,我的这个程序为什么一直报错啊??!

  • 只看楼主
  • 收藏

  • 回复
  • 丶这道路有点黑
  • 超能力者
    9
该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
各位大佬我的程序莫名报错,调了一个上午,把能改的地方都改了,也不知道怎么回事求大佬们看看帮帮忙啊!!
程序逻辑很简单,就是读取文件,每行存到一个堆上的字符串里,最后free内存,分配堆内存函数多了个统计一共分配了多少内存的功能。
程序执行到main函数中的while块分配内存语句时,有时报错有时不报错(符号未加载、出发了一个断点、引起了一个异常等错误),在最后的free_pstring中肯定报错!
有没有大佬能帮帮忙啊,哭了ToT
// global.h
extern size_t mem; // 内存分配总量
extern size_t cmpnum; // 比较次数
// global.c
size_t mem = 0; // 内存分配总量
size_t cmpnum = 0; // 比较次数
// provided.h
#include "pstring.h"
void* bupt_malloc(size_t size);
int byte_cmp(char a, char b);
// provided.c
#include "provided.h"
#include "global.h"
#include "pstring.h"
#include<stdio.h>
#include<string.h>
void* bupt_malloc(size_t size){
if (size <= 0)
return NULL;
mem += size;
return malloc(size * sizeof(char));
}
int byte_cmp(char a, char b){
++cmpnum;
return (a - b);
}
// pstring.h
#include<string.h>
typedef struct Pstring{
char *pstring;
}Pstring;
void init_pstring(Pstring* ps, const char *str);
void free_pstring(Pstring *ps);
// pstring.c
#include "provided.h"
#include "pstring.h"
#include<string.h>
void init_pstring(Pstring* ps, const char *str){
int len = strlen(str) + 1;
ps->pstring = (char*)bupt_malloc(sizeof(char) * len);
strcpy(ps->pstring, str);
}
void free_pstring(Pstring *ps){
free(ps->pstring);
}
// Main.c
#include<stdio.h>
#include<string.h>
#include "provided.h"
#include "pstring.h"
#include "global.h"
int main(){
FILE* fp = fopen("test.txt", "r");
char line[256];
memset(line, 0, 256);
Pstring *ps = (Pstring*)bupt_malloc(10 * sizeof(Pstring));
int t = 0;
size_t size_of_pstring = sizeof(Pstring*);
while (!feof(fp)){
fgets(line, 255, fp);
init_pstring(ps+t*size_of_pstring, line);
++t;
}
for (int j = 0; j < 10; ++j){
free_pstring(ps + j * size_of_pstring);
}
free(ps);
fclose(fp);
return 0;
}


  • GTA小鸡
  • 吧主
    14
该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
你只申请了一次内存但释放了10次,而且释放的位置不是申请的位置,当然报错
而且你没有考虑malloc是否成功就直接往mem上加size


2025-07-17 20:57:53
广告
  • 丶这道路有点黑
  • 超能力者
    9
该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
test.txt的内容就10行,ANSI编码:
s
str2
string5
一二
12345678
一
5
5
5
5


登录百度账号

扫二维码下载贴吧客户端

下载贴吧APP
看高清直播、视频!
  • 贴吧页面意见反馈
  • 违规贴吧举报反馈通道
  • 贴吧违规信息处理公示
  • 11回复贴,共1页
<<返回c语言吧
分享到:
©2025 Baidu贴吧协议|隐私政策|吧主制度|意见反馈|网络谣言警示