以下是我的计划。我正在创建一个结构,使用malloc来分配内存,因为我想要一个非常大的结构数组,然后将该结构数组传递给函数。功能并不重要,因为我无法摆脱主程序。我的困惑是我的编译器(gcc)说当我试图释放它时,every_event是未声明的,但是没有其他地方。当我注释掉它编译的自由语句时,但是当我执行each_event [i] .timestamp = tim [i]行时,valgrind说我写了大小4的无效。上面的行被注释掉了因为valgrind告诉我错误在那里(我使用gcc -g -O0编译),即使我知道它必须表示下面的行。
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#define event_length 512
#define bits_n_byte 8
#define timestamp_bytes 8
typedef enum type {
DATA, CLOCK, EXPECTED, SPILL, ALL
} type;
typedef struct event {
char clocbuffer[event_length*bits_n_byte];
char datbuffer[event_length*bits_n_byte];
char expect[event_length];
char spil[event_length];
char clocerror[event_length*bits_n_byte];
char daterror[event_length*bits_n_byte];
long unsigned int timestamp;
} event;
int i, j, k, l, length, nevents;
char **spil, **expect, **dat, **cloc, **clocerror, **daterror;
long unsigned int *tim;
char library[256];
char *runnum, *clocmode, *datmode;
void GetPiece(char*, type, struct event*);
void FindMode(type);
void ErrorPiece(type);
int main(int argc,char **argv) {
if (argc != 2) {fprintf(stderr, "Format: ./program #_patterns\nTry again.\n");}
for (i=0;i<256;i++) library[i]=i;
FILE *IN = NULL;
char *buffer = NULL;
runnum = (char *) malloc(2);
runnum = strncpy(runnum,argv[1],1);
runnum[1] = '\0';
IN=fopen(argv[1], "r"); /*Open input file.*/
if (IN)
{
fseek(IN, 0, SEEK_END); /*This finds */
length = ftell(IN); /*the length */
fseek(IN, 0, SEEK_SET); /*of the file.*/
buffer = malloc(length + 2); /*for buffer. */
fread(buffer, 1, length, IN);
tim = (long unsigned int *) malloc(length + 2*sizeof(long unsigned int));
fread(tim, sizeof(long unsigned int), length/sizeof(long unsigned int), IN);
fclose(IN);
nevents = length/2056;
struct event* each_event = (struct event *) malloc(nevents*sizeof(struct event));
for (i=0; i<length/sizeof(unsigned long int); i+=2056/sizeof(unsigned long int))
{
tim[i] = __builtin_bswap32 (tim[i]);
tim[i]-=0x80000000;
//if (tim[i]<1200000000 || tim[i]>1300000000) fprintf(stderr, "Check timestamp. Either endianness, size of bytes, or size of long ints are different.");
each_event[i].timestamp = tim[i];
}
clocmode = malloc(nevents);
datmode = malloc(nevents);
GetPiece(buffer, DATA, each_event);
GetPiece(buffer, CLOCK, each_event);
GetPiece(buffer, EXPECTED, each_event);
GetPiece(buffer, SPILL, each_event);
GetPiece(buffer, ALL, each_event);
FindMode(DATA);
FindMode(CLOCK);
ErrorPiece(DATA);
ErrorPiece(CLOCK);
}
else fprintf(stderr,"Error in file naming/opening.\n"); /*error*/
free (buffer);
free (tim);
free (runnum);
free (clocmode);
free (datmode);
free (each_event);
return 0;}
答案 0 :(得分:0)
因为在each_event
块中声明了if { ... }
,所以当您尝试free()
时,它已超出范围。要么在if { ... }
的末尾释放它,要么在main()
的开头将声明与其他声明放在一起。但是,如果你使用后者,你可能会收到关于它可能被使用但没有被初始化的警告,所以第一个选项可能是最好的。