c-内存分配错误-在Linux中,但在OSX Unix中没有



我正在为一个统计数据包编写一些代码,首先将数据读入指针数组。我初始化指针并使用malloc分配足够的内存;然而,我有时会在下面代码的末尾出现内存分配错误。

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include "stats.h"
int main(int argc, char **argv) {
FILE *fp, *outFile, *outBin;    // create a file identifier
size_t n, nbins; // # of data points
double *data; // pointer to hold data
double average, variance, *med; // stat returns
int medianComplete, histComplete, i; // return 1 on success
hist_t *Histogram;
// read in the number of bins from exe arguments
nbins = atoi(argv[1]);
nbins = (size_t)nbins;
// open the binary datafile and read in first value
// which is number of data points
// use exe input for filename
fp = fopen(argv[2],"rb");
fread(&n, sizeof(size_t),1,fp);
// allocate enough memory to hold all data
data = (double*)malloc(sizeof(double)*n);
if (!data)
    printf("Memory allocation error");
fread(data,sizeof(double),n,fp);

这个程序在我的个人计算机(MacOSX)上编译并运行良好,但当我试图在Linux服务器上运行它时,由于分段错误而失败。我用Valgrind看看我是否能找到错误,我收到了以下结果。

==8641== Warning: silly arg (-501426814648844128) to malloc()
==8641== Invalid write of size 1
==8641==    at 0x4C2B20D: mempcpy (mc_replace_strmem.c:956)
==8641==    by 0x4EA2F15: _IO_file_xsgetn (fileops.c:1423)
==8641==    by 0x4E971D2: fread (iofread.c:44)
==8641==    by 0x40086D: main (runstats.c:28)
==8641==  Address 0x0 is not stack'd, malloc'd or (recently) free'd

这是我写的第一个使用指针的程序,我不知道为什么它能在一个系统上工作,而不能在另一个系统中工作。

sizeof(size_t)依赖于平台。在具有默认32位代码的OSX上,size_t是4个字节。在64位Linux上,size_t是8个字节。如果您在64位Linux上运行,那么您读取的n与在32位OSX上读取的不同。

如果必须使用二进制数据格式,请不要将平台特定类型的大小用作字段大小。决定文件头是4字节还是8字节,小端还是大端,并一致使用。

请参阅:什么';s在32位上的sizeof(size_t)与各种64位数据模型的比较?

在发布之前,您肯定应该格式化您的源代码。。。

在执行fread(&n, sizeof(size_t),1,fp);之后,使用调试器或打印n的值。似乎你没有得到你期望的价值。

相关内容

最新更新