程序
我正在用C写一个程序,它可以读取多项式系数的文档,并可以评估多项式的根。
在我的一个函数中,我试图读取文本文件,并创建一个"多项式"列表。多项式的定义如下:
typedef struct
{
unsigned int nterms; /* number of terms */
double complex *polyCoef; /* coefficients */
} polynomial;
文本文件采用以下格式,其中每行代表一个多项式,每个数字代表一个系数:
1 0 0 0 2 -1
16 70 -169 -580 75
1 0 4 0 -5
0 -9 3 5 -3
5 -4 3 -2 0
1.0 -3.4 5.4531 -4.2077 1.5092 -0.2030
<标题>
我在我的实现尝试中得到一些奇怪的行为。使用下面的代码,我得到
*在'。/hw6': corrupt double-link list: 0x0000000000a1c240 *
PolyFile = fopen(argv[2], "r");
if(NULL == PolyFile){ /* If the file fails to open */
fprintf(stderr, "Error: Input file '%s' not foundn", argv[2]);
return(-1);
}
/****** Read in the polynomials *************/
polynomials = malloc(sizeof(polynomial*) * size); /* Initialize */
if(polynomials == NULL){
fprintf(stderr, "%s %i: Could not allocate memoryn", __FILE__, __LINE__);
exit(-99);
}
/* Read all of the data from the file */
while(fgets(String, MAX_STR_LEN, PolyFile)) {
strLen = strlen(String); /* Determine size of line */
/* Ensure that the line is not too long */
if(strLen <= MAX_STR_LEN){
/* Create the polynomial */
p = (polynomial*)malloc(sizeof(polynomial));
token = strtok(String, " ");
while(token){
coefficients[coeffCount] = token;
token = strtok(NULL, " ");
coeffCount++;
}
createPoly(p, coeffCount);
/* Set p->polyCoef to the reverse of coefficients */
for(int lcv = 0; lcv <= coeffCount - 1; lcv++){
p->polyCoef[lcv] = atof(coefficients[coeffCount - lcv - 1]) + 0.00*I;
}
coeffCount = 0;
polynomials[size] = p;
printf("P->NTERMS: %in", p->nterms);
size++;
} else {
fprintf(stderr, "%s %i: Line too long. Polynomial ignoredn",
__FILE__, __LINE__);
}
}
fclose(PolyFile);
/**************************/
for(int j = 0; j <= size - 1; j++){
printf("J: %in", j);
printf("IN FOR LOOP: %in", (polynomials[j])->nterms);
// printPoly(polynomials[j]);
printf("n");
}
…
/*---------------------------------------------------------------------------
Creates a polynomial data structure with nterms. This allocates storage
for the actual polynomial.
Where: polynomial *p - Pointer to polynomial data structure to create
unsigned int nterms - The number of elements to create
Returns: nothing
Errors: prints an error and exits
---------------------------------------------------------------------------*/
void createPoly(polynomial *p, unsigned int nterms){
int lcv; /* loop control variable */
/* Create a polynomial struct */
p->nterms = nterms;
p->polyCoef = (double complex*)malloc(sizeof(double complex)*nterms);
/* Error out if problem with malloc */
if(p->polyCoef == NULL){
fprintf(stderr, "%s %i:Error allocating memoryn", __FILE__, __LINE__);
exit(1);
}
/* Set the coefficients to 0 */
for(lcv = 0; lcv < nterms; lcv++){
(p->polyCoef)[lcv] = 0.00 + 0.00*I;
}
}
如果我删除fclose(PolyFile);
,代码继续,但是调试打印显示polynomials[0]->nterms
等于一个随机的、变化的、非常大的数字。我不知道为什么会这样。
出现问题的原因是polynomials
初始化时,size
等于0:
polynomials = malloc(sizeof(polynomial*) * size);
通过使用文件中的行数分配适当的大小来解决这个问题。