我正在编写这个 C 代码,它接收一个文件并从中读取值,该代码还没有做任何事情,但这是我到目前为止所拥有的。程序在调用四个 malloc 的块中崩溃。如果我注释掉 y、f 和 yp,程序运行良好。我不知道是什么原因造成的。因此,任何帮助将不胜感激。
注意:我正在使用 gcc 在 ubuntu 上对此进行测试。我确实尝试将 malloc 强制转换为“(float *)”,但我仍然遇到同样的错误。
int main( int argc, char *argv[])
{
FILE *rhs, *output;
int niter, n, i = 0, j = 0, k = 0, n1 = n + 1;
rhs = fopen(argv[1], "r");
// ab+ opens file for writting and creates the file if need be
output = fopen(argv[2], "ab+");
niter = atoi(argv[3]);
// check if files open up or not, if not exit.
if((rhs == NULL) || (output == NULL))
{
printf("Error Opening files.\n");
exit(1);
}
// read in N
fscanf(rhs, "%d", &n);
// THIS IS THE BLOCK CAUSING THE CRASH
// CODE WORKS WHEN I COMMENT OUT LINES AND ONLY LEAVE ONE OF THEM IN
// generate array to hold values from rhs file
float *numbers = malloc(sizeof(float) * ((n1)*(n1)));
float *y = malloc(sizeof(float) * ((n1)*(n1)));
float *f = malloc(sizeof(float) * ((n1)*(n1)));
float *yp = malloc(sizeof(float) * ((n1)*(n1)));
// get numbers and store into array
while(fscanf(rhs, "%f", &numbers[i]) != EOF)
{
printf("In while %f\n", numbers[i]);
i++;
}
fclose(rhs);
return 0;
}