首页 > 解决方案 > C的内存分配错误?定义未使用的变量时,代码有效;否则崩溃

问题描述

我是一个新手 C 程序员,完全坚持调试依赖 CFITSIO 包的程序[如果我在下面弄错术语,请提前抱歉]。我正在阅读两个适合:1.“BFmask.fits”,2.“DFmask.fits”。这是两个以 1 或 0 作为元素的文件。

它们被定义为双精度指针,如下所示: double *maskdark,*maskbright;

内存分配如下:

maskdark=malloc(size*sizeof(double)); //dark mask
maskbright=malloc(size*sizeof(double)); //bright mask

其中“size”是一个长变量,值为 490000

问题:当我执行程序时,它显然没有正确读取 BFmask.fits 或 DFmask.fits (即没有正确读取 maskbright 或 maskdark 的条目)。

但是,当我声明第三个变量“掩码”(即双 *掩码;)时,程序会正确执行。

  1. 这个问题的原因和解决方法是什么?
  2. 以后如何避免类似的情况?

我已经检查了几十次以确保在程序的任何地方都没有使用这个变量。这对我来说毫无意义。

 #include <stdio.h>

 //For declaration of open, close
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <math.h>
 #include <unistd.h>
 #include <time.h>
 //GSL Matrix STuff
 #include <gsl/gsl_vector.h>
 #include <gsl/gsl_math.h>
 #include <gsl/gsl_matrix.h>
 #include <gsl/gsl_eigen.h>
 #include <gsl/gsl_blas.h>
 //CFITSIO
 #include <fitsio.h>
int main ()
{
long sizetotdm,cmwfsbrightindex,cmwfsdarkindex;
long size,sizex,sizey;
double *maskdark,*maskbright;
//double *mask; //if I uncomment this, then the program works   properly somehow
fitsfile *fptr;
float nullval;
int  status, anynull;

cmwfsbrightindex=0;
cmwfsdarkindex=0;
sizex=700; sizey=700; size=sizex*sizey;

/* Define Masks for Dark Field and Bright Field */
maskdark=malloc(size*sizeof(double)); //dark mask
maskbright=malloc(size*sizeof(double)); //bright mask

/* Read in Dark and Bright Field Mask files */
sprintf(s_file,"./06_21_19_mask/BFmask.fits");
fits_open_file(&fptr,s_file,READONLY,&status);
   fits_read_img(fptr,TDOUBLE,1,size,&nullval,maskbright,&anynull,&status);


sprintf(s_file,"./06_21_19_mask/DFmask.fits");
fits_open_file(&fptr,s_file,READONLY,&status);
fits_read_img(fptr,TDOUBLE,1,size,&nullval,maskdark,&anynull,&status);

for (i=0;i<size; i++)
 {
  if (*(maskbright+i)==1)
   {
     cmwfsbrightindex+=1;
      }
  if (*(maskdark+i)==1)
   {
     cmwfsdarkindex+=1;
      }
  }

printf("the number of pixels is %ld %ld     \n",cmwfsbrightindex,cmwfsdarkindex);
}

结果应该...

the number of pixels is 24212 24952 //this happens when I define an unused variable

结果是...

the number of pixels is 0 0  //this happens when I comment out the unused variable

标签: c

解决方案


推荐阅读