【发布时间】:2017-08-21 06:28:50
【问题描述】:
我一直在从事一系列涉及结构的任务,在 c 中读写 bin 文件。
结构体定义为:
struct Data{
unsigned int a;
unsigned short b;
short c;
char d[8];
short e;
int f;
int g;
short h;
char i;
char j;
unsigned long k;
char l;
double m;
float n;
int o;
char p;
double q;
}
我的阅读和打印程序似乎工作正常,代码是:
int main (int argc, char **argv){
// Check correct number of args
FILE *record = fopen(argv[1], "r")
// More Prelim checks
struct Data entry;
/* if first field exists, task assumption is that all other fields
* must also exist with the proper sizes.
*/
while(fread(&entry.a, sizeof entry.a, 1, record) > 0){
fread(&entry.b, sizeof entry.b, 1, record);
// ... read all fields one by one
fread(&entry.q, sizeof entry.q, 1, record);
printf("%u, %d, %d, %s, %d, %d, %d, %d, %c, %lu, %hhx, %f, %f, %d, %d, %f",
entry.a, entry.b, entry.c . . . entry.q);
}
}
这会打印出输入 bin 文件而没有错误(针对 15 个文件自动测试,其中一些包含数十个条目)。最简单的,也就是一个入口,就是
但是,当我尝试使用以下数组存储所有数据以便对其进行排序时,数据开始正确,但据我所见,随后完全失控:
struct Data *entries = NULL;
int curEntries = 100;
int counter = 1;
entries = (struct Data *) malloc(curEntries * sizeof(struct Data));
while(fread(&entries[counter - 1].a, sizeof entries[counter - 1].a, 1, record) >0){
/* Same reading, storing and printing as above, then increment counter */
}
由于读取和打印部分完全相同,除了使用“计数器”变量之外,我的问题与数组内存有关吗?我需要解决什么问题?
【问题讨论】:
-
请向我们展示非工作程序的Minimal, Complete, and Verifiable Example。记得向我们展示您的
#include。 -
尝试创建一个minimal reproducible example 暴露问题。 MCVE 的一种方法是简化结构(少得多的字段)。
-
我还建议阅读 Eric Lippert 的 How to debug small programs,并学习如何使用调试器逐行执行代码,同时监控变量及其值。此外,您可以考虑使用Valgrind 之类的工具来检测内存和指针问题。
-
对了,为什么将
counter初始化为1,然后全部使用counter - 1呢?为什么不简单地将其初始化为0? -
您是否考虑过二进制文件损坏的可能性?
标签: c arrays memory struct bin