gpt4 book ai didi

c - 段错误数组在 ubuntu 中 float 但在 osx 中不 float

转载 作者:太空宇宙 更新时间:2023-11-04 03:43:07 24 4
gpt4 key购买 nike

如果我在 osx 上用 gcc 编译这段代码并运行它,它工作得很好......事实上,如果我在 ubuntu(gcc 版本:4.8.2)上编译相同的代码并运行它,我有一个分段故障错误。为什么?

#include <stdio.h>
#include <stdlib.h>

#define ROW 64
#define COL 16

int readMyFile(float*, char**);

int main(int argc, char *argv[])
{
float *array;
array = (float*) malloc (ROW*COL*sizeof(float));

r = readMyFile(array,argv);
if(r) return r;

free(array);

return 0;
}


int readMyFile(float *array, char* argv[]) {

FILE *ifp;
float tmp;
short i=0;

ifp=fopen(argv[1], "r");

if(ifp==NULL)
return 1;

while(fscanf(ifp, "%f", &tmp) == 1)
{
printf("i: %d\n",i);
array[i]=tmp;
i++;
}
fclose(ifp);
return 0;
}

我编译上面的代码,在 Ubuntu 14.04 LTS 上使用命令:gcc -o Test Test.c之后,我使用此命令运行:./Test myfile.txt

myfile.txt的内容是这样的:

-40-3-22个02个01个...等等

在我看来,问题可能出在这一点上:matrix[i]=tmp; 为什么?

最佳答案

有两个地方你应该添加错误处理:

int main(int argc, char *argv[])
{
float *array;
array = (float*) malloc (ROW*COL*sizeof(float));

// Added check that malloc succeded.
if (array == NULL) return 1; // Failed to allocate memory

r = readMyFile(array,argv);
if(r) return r;

free(array);

return 0;
}


int readMyFile(float *array, char* argv[]) {

FILE *ifp;
float tmp;
int i=0; // Change type to int to be able to handle larger sizes.

ifp=fopen(argv[1], "r");

if(ifp==NULL) // Good!
return 1;

while(fscanf(ifp, "%f", &tmp) == 1)
{
// Added check that there is room in array.
if (i >= ROW * COL) return 1; // Too many values in the file!
printf("i: %d\n",i);
array[i]=tmp;
i++;
}
fclose(ifp);
return 0;
}

编辑:

显然该文件包含超过 64*16 个值,因此在这种情况下,由于文件中的值太多,代码将退出。

关于c - 段错误数组在 ubuntu 中 float 但在 osx 中不 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26928355/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com