我有一个基本上看起来像这样的程序:
typedef struct cpl_def
{
int A;
int B;
int OK;
struct cpls *link;
}cpls;
int main(void)
{
int n1, n2;
int num = 300; /* say */
int *a;
a = NULL;
int *apt;
int *b;
b = NULL;
int *bpt;
cpls *cplptr;
cplptr = NULL;
int i, j;
for (i=0; i < 2000; i++)
{
if (i == 0)
{
cplptr = (cpls *) malloc(num*sizeof(cpls) ); /* create the structure */
initalize(cplptr);
}
/*
...operations on cplptr ... */
FOO(cplptr);
/*
...determine I need a subset of size n1 (a positive integer of size n1 which changes during the loop) entries from cplptr ... */
n1 = FOO2(cplptr);
n2 = FOO3(cplptr);
/*
...figure out the values of A, B for additional n2 entries into cplptr ...
*/
cplptr2 = (cpls *) malloc(n2*sizeof(cpls) ); /* a second structure to store additional entries */
/* .... operations on cplptr2 ...*/
/* ...copy subset of n1 entries from cplptr into dynamically allocated arrays a,b of size n1... */
a = malloc(n1 * sizeof(int));
apt = &a[0];
b = malloc(n1 * sizeof(int));
bpt = &b[0];
for (j=0; j < num; j++)
{
if (cplptr[j].OK==1)
{
(*apt++) = cplptr[j].a;
(*bpt++) = cplptr[j].b;
}
}
free(cplptr); /* free the first structure */
cplptr = (cpls *) malloc((n1+n2)*sizeof(cpls) ); /* redeclare the first structure to reflect the proper sizes */
for (j = 0; j < n1; j++) /* transfer a subset of size n1 to the first structure */
{
cplptr[j].a = a[j];
cplptr[j].b = b[j];
cplptr[j].OK = 1;
}
for (j = n1; j < n1 + n2; j++) /* transfer things to the first structure */
{
cplptr[j].a = cplptr2[j].a;
cplptr[j].b = cplptr2[j].b;
cplptr[j].OK = cplptr2[j].OK;
}
free(a)
free(b)
free(cplptr2); /* free the second structure */
} /* End iteration i
} /* End main() */
这只是骨架形式,但它希望能提供足够的图片。无论如何,它通常运行良好,但对于 n1、n2 的某些值,free(cpplptr) 似乎会导致分段错误。它只被调用一次,我在 malloc() 调用 cplptr 之后和 cplptr 的相应 free() 之前检查地址。
....
cplptr = (cpls *) malloc(num*sizeof(cpls) );
printf("fine to this %p\n", &cplptr[0]);
...
printf("fine to this %p\n", &cplptr[0]);
free(cplptr) <- segmentation fault happens here.
地址匹配,这意味着 free() 应该释放它应该释放的东西,对吧?gdb 给出程序接收到的信号 SIGSEGV,分段错误。0xb7ce179b 在?? () 来自 /lib/tls/i686/cmov/libc.so.6 和步骤找不到当前函数的边界
有没有另一种方法来实现类似的东西来避免分段错误?
感谢一百万您的建议!知道发生了什么吗?