c - 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 的条目)。
但是,当我声明第三个变量“掩码”(即双 *掩码;)时,程序会正确执行。
- 这个问题的原因和解决方法是什么?
- 以后如何避免类似的情况?
我已经检查了几十次以确保在程序的任何地方都没有使用这个变量。这对我来说毫无意义。
#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
解决方案
推荐阅读
- python - 如何将列表更改为字典
- html - Angular - (文件)输入在文件选择时不规则
- c - 从文件中读取并将其存储到 c 中长度未知的字符串中
- r - 使用 switch 从 ggplot2 函数中转换变量
- php - 未定义的属性:App\Http\Controllers\PostController::$p
- java - AnonPages 是什么的一部分?记忆问题
- python - 如何读取以空格分隔的数字并删除重复项?
- amazon-web-services - Terraform:使用公共 IP 地址访问安装在 Bowser 上的 apache 的 EC2 实例只是不断加载、加载和加载
- javascript - 创建 Javascript 组件的最佳方法是什么?
- wordpress - 如何修复通过 data:image/gif;base64 添加到我的网站创建的 404 错误?