我已经创建了一个结构:
struct SeqInfo
{ int Len;
int uncLen;
int *uncIndex;
char *seq;
char *seqc;
char *seqr;};
我malloc
空间并在函数中初始化一个结构体:
void initSeqInfo(struct SeqInfo *SI, char *seq, char *seqc, char *seqr){
int lenTemp;
int lenUnc;
// length of the seq and uncertain
lenTemp = strlen(seq);
lenUnc = Num_uncertains(seqr);
// make space
SI->seq = (char *)malloc(sizeof(char)*lenTemp);
SI->seqc = (char *)malloc(sizeof(char)*lenTemp);
SI->seqr = (char *)malloc(sizeof(char)*lenTemp);
SI->uncIndex = (int *)malloc(sizeof(int)*lenUnc);
// init seq
SI->Len = lenTemp;
SI->uncLen = lenUnc;
// init index
Index_uncertains(seqr, SI->uncIndex);
// init seq
strcpy(SI->seq, seq);
strcpy(SI->seqc, seqc);
strcpy(SI->seqr, seqr);
}
我还定义了一个函数来释放空间,如下所示:
// free space for structure SeqInfo
void freespace(struct SeqInfo SI){
free(SI.seq);
free(SI.seqc);
free(SI.seqr);
free(SI.uncIndex);
}
我定义了一个指向该结构的指针并按如下方式初始化它:
struct SeqInfo *SeqRNAs;
SeqRNAs = (struct SeqInfo*)malloc(sizeof(struct SeqInfo)*NumComb);
initSeqInfo(&SeqRNAs[0], seq10, struct10_con, struct10_req);//A1P2
initSeqInfo(&SeqRNAs[1], seq13, struct13_con, struct13_req);//A3P1
initSeqInfo(&SeqRNAs[2], seq4, struct4_con, struct4_req);//P1P4
initSeqInfo(&SeqRNAs[3], seq14, struct14_con, struct14_req);//A3P2
initSeqInfo(&SeqRNAs[4], seq17, struct17_con, struct17_req);//A4P2
initSeqInfo(&SeqRNAs[5], seq18, struct18_con, struct18_req);//A4P3
当我尝试为定义的 SeqRNAs[]
释放空间时出现问题:
for(i = 0; i < NumComb; i++){
freespace(SeqRNAs[i]);
}
错误是:
*** glibc detected *** ./Blocks14E: free(): invalid next size (fast): 0x0000000001123210 ***
为什么会出现此错误?我很确定这是我释放空间的唯一地方。
最佳答案
您正在调用需要空终止符的 strcpy()
,因此您需要确保为空终止符留出空间。您当前的代码不包含空终止符的空间:
lenTemp = strlen(seq);
....
SI->seq = (char *)malloc(sizeof(char)*lenTemp);
....
strcpy(SI->seq, seq);
更改为:
lenTemp = strlen(seq);
....
SI->seq = (char *)malloc(sizeof(char)*(lenTemp + 1));
....
strcpy(SI->seq, seq);
SI->seqc
和 SI->seqr
相同
关于c - 如何释放结构数组中的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33880899/